简体   繁体   中英

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 }]
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;
})

This is a short solution with linear complexity, O(n+m) , and with the help of a Map .

 var users = [{ name: 'Alice', typeID: 1 }, { name: 'Bob', typeID: 2 }, { name: 'Carol', typeID: 3 }], authorized = [{ typeID: 1 }, { typeID: 2 }], map = new Map, result; authorized.forEach(a => map.set(a.typeID, true)); result = users.filter(a => map.has(a.typeID)); console.log(result); 

You can use

var types = authorized.reduce(function(types, type) { types.push(type.typeID); return types; }, []);

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

maybe there is a more efficient solution, but it is something to start with

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM