Greg Gum
Greg Gum

Reputation: 37919

How to write an array filter that returns all items of array that is in another array

assignedRoles = ['User','InCharge'];
items = ['Admin','Supervisor','User', 'InCharge'];

I need a filter that will return all items which are in assignedRoles.

So in the above example, the filter would return 'User' and 'InCharge'

This is what I have tried:

return items.filter(a=> a.any(assignedRoles);

Upvotes: 0

Views: 44

Answers (2)

Sherali Turdiyev
Sherali Turdiyev

Reputation: 1743

Just use assignedRoles.indexOf() !== -1 ( x !== -1 is faster than x > -1 and x >= 0 )

var assignedRoles = ['User', 'InCharge'];
    var items = ['Admin', 'Supervisor', 'User', 'InCharge'];
    
    var result = items.filter(function(item) {
      return assignedRoles.indexOf(item) !== -1;
    });
    
    console.log(result);

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30567

Use indexOf()

var assignedRoles = ['User', 'InCharge'];
var items = ['Admin', 'Supervisor', 'User', 'InCharge'];

var answer = items.filter(function(item) {
  return assignedRoles.indexOf(item) > -1;
});

console.log(answer);

Upvotes: 5

Related Questions