Want to hide some categories from the categories meta box in the post editor for the two specific user roles

After searching a lot over the web I found a solution, so I am answering my own question. I hope it might help others. you can pass in the ids of categories you want to hide as an array, and then paste this in your functions.php file. It will work in the new editor. All categories will be shown for administrators.

Don’t forget to customize the values in the $exclude_array =
array(“5″,”6″,”7″,”1”);

function hide_categories_for_specific_user( $exclusions, $args ){

if (!current_user_can('manage_options') ) {

   // IDs of terms to be excluded
   $exclude_array = array("5","6","7","1"); // CHANGE THIS TO IDs OF YOUR TERMS


   // Generation of exclusion SQL code
   $exterms = wp_parse_id_list( $exclude_array );
   foreach ( $exterms as $exterm ) {
           if ( empty($exclusions) )
                   $exclusions=" AND ( t.term_id <> " . intval($exterm) . ' ';
           else
                   $exclusions .= ' AND t.term_id <> ' . intval($exterm) . ' ';
   }

   // Closing bracket
   if ( !empty($exclusions) )
       $exclusions .= ')';

   // Return our SQL statement
   return $exclusions;

  }
}

 // Finally hook up our filter
 add_filter( 'list_terms_exclusions', 'hide_categories_for_specific_user', 10, 2 );