Search code examples
javascriptecmascript-6lodash

Iterating and filtering with ES6/lodash


We have an array of objects like:

const persons = [{
    name: "john",
    age: 23
}, {
    name: "lisa",
    age: 43
}, {
    name: "jim",
    age: 101
}, {
    name: "bob",
    age: 67
}];

And an array of a attribute values of the objects in object

const names = ["lisa", "bob"]

How can we find persons with name in the names array using es6, like:

const filteredPersons = [{
    name: "lisa",
    age: 43
}, {
    name: "bob",
    age: 67
}];

Solution

  • ES6

    Use filter function with predicate and in it check the existence of the name in the names array.

    const persons = [
        {name: "john", age:23},
        {name: "lisa", age:43},
        {name: "jim", age:101},
        {name: "bob", age:67}
    ];
    
    const names = ["lisa", "bob"];
    
    const filtered = persons.filter(person => names.includes(person.name));
    
    console.log(filtered);