0

Have an array of objects

var objArray = [{name: orange, id: 1},{name : apple, id:2},{name: banana, id:3},{name: grapes, id:4}]

and an array of id's

var arrId = [1,4]

How can i filter to get corresponding object of matching id from array of objects?

Expected:

var result = [{name: orange, id: 1}, {name: grapes, id:4}]

Tried:

objArray.filter(o => o.id === arrId);
New123
  • 219
  • 1
  • 4
  • 13
  • 1
    Does this answer your question? [How to filter an array from all elements of another array](https://stackoverflow.com/questions/34901593/how-to-filter-an-array-from-all-elements-of-another-array) – Nick Sep 15 '20 at 07:31

1 Answers1

1

You could check with Array#includes.

var objArray = [{ name: 'orange', id: 1 }, { name: 'apple', id: 2 }, { name: 'banana', id: 3 }, { name: 'grapes', id: 4 }],
    arrId = [1, 4],
    result = objArray.filter(o => arrId.includes(o.id));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392