Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}];
like image 518
kallada Avatar asked Dec 11 '22 07:12

kallada


2 Answers

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);
like image 138
Suren Srapyan Avatar answered Dec 14 '22 22:12

Suren Srapyan


You can use filter() and inlcudes() to get required result.

DEMO

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

console.log(persons.filter(({
  name
}) => names.includes(name)))
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 40
Narendra Jadhav Avatar answered Dec 14 '22 23:12

Narendra Jadhav