0

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 }]
3
  • 1
    Please include attempted solutions, why they didn't work, and the expected results. That would really helps us to figure out the issue with your code. Thanks! Commented Jul 6, 2016 at 10:22
  • 1
    Use .map and .filter Commented Jul 6, 2016 at 10:22
  • 1
    Array.prototype.filer() and a loop Commented Jul 6, 2016 at 10:23

3 Answers 3

3
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;
})
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

O(m + n) ~ O(2n) ~ O(n)
@mortezaT, what means ~ in this case?
They're similar and can be replaced; O(n) and O(2n) considered as O(n).
i know. any linear content stays linear.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.