Riccardo Riccardo - 5 months ago 42
jQuery Question

Javascript / JQuery Array of objects intersection by property

Given two arrays:

var users = [{ name: 'Alice', typeID: 1 }, { name: 'Bob', typeID: 2 }, { name: 'Carol', typeID: 3 }];
var authorized = [{ typeID: 1 }, { typeID: 2 }];


I would like to know the simplest way to get all users having typeId that is present in the authorized array.

In this case the result should be:

[{ name: 'Alice', typeID: 1 }, { name: 'Bob', typeID: 2 }]

Answer
var result = users.filter(function(user) {
  return authorized.some(function(authorizedObj) {
    return authorizedObj.typeID === user.typeID;
  });
})

Should be noted that if your authorized array contained just the ID's and not objects (something like [1, 2]), then the solution would be simpler:

var result = users.filter(function(user) {
  return authorized.indexOf(user.typeID) !== -1;
})