Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Underscore.js to filter an array of objects on a property using a 'contains'

I have an array of objects which I would like to filter using a contains/any method on a property using underscore.

For example, if I had the following variables:

var people = [
{
    name: 'Dave',
    age: 26
},
{
    name: 'Frank',
    age: 23
}];
var allowedAges = [20, 23, 24];

I would like to use underscore to end up with a result like:

 var allowedPeople = [];
 _.each(_.where(people, { age: _.any()}), function (person) {
            allowedPeople.push(person);
        });

And there may also be occasions where allowedAges is an array of objects and id want to use the contains/any on the people array using a property of the objects in allowedAges.

like image 411
Grant Avatar asked Mar 30 '16 14:03

Grant


2 Answers

The JS equivalent of contains is usually indexOf (and find in rare cases).

You can use the built-in Array.prototype.filter to do this like:

people.filter(function (person) {
  return allowedAges.indexOf(person.age) !== -1; // -1 means not present
});

or with underscore, using the same predicate:

_.filter(people, function (person) {
  return allowedAges.indexOf(person.age) !== -1; // -1 means not present
}

If you have access to ES6 collections or a polyfill for Set, you can replace the allowedAges array with a set (enforcing unique values) and simply use Set.prototype.has:

people.filter(person => allowedAges.has(person.age))
like image 65
ssube Avatar answered Nov 17 '22 12:11

ssube


For the sake of completeness, here's an underscore solution that works with a mixed array of integers and objects containing an age property.

var allowedPeople = _.filter(people, (p) =>
  _.some(allowedAges, (a) => (a.age || a) === p.age)
);
like image 24
Aldehir Avatar answered Nov 17 '22 12:11

Aldehir