0

Like i have an array of objects:

const arr = [
{name: 'Adam', age: 23},
{name: 'Steve', age: 23},
{name: 'Eve', age: 30}
];

And i have another object

let obj = {age: 23}

How can I filter an array so it will be contain just:

 [
    {name: 'Adam', age: 23},
    {name: 'Steve', age: 23},
 ];
ZAPE
  • 19
  • 1
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – evolutionxbox May 25 '22 at 12:24
  • 1
    Try `arr.filter(a => a.age === obj.age)` – Karan May 25 '22 at 12:26
  • 1
    Please visit [help], take [tour] to see what and [ask]. Do some [research, search for related topics on SO](https://www.google.com/search?q=How+to+filter+an+array+of+objects+by+another+object?+site:stackoverflow.com); if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – mplungjan May 25 '22 at 12:26
  • @mplungjan I'm struggling to find a dupe target – evolutionxbox May 25 '22 at 12:27
  • `const filterAge = obj.age; const result = arr.filter(({age}) => age === filterAge)` – mplungjan May 25 '22 at 12:29
  • A more interesting problem would be applying a general filter object with an unknown number unknown keys. So you could have just `age`, just `name` or both in the filter object and an element of `arr` is filtered if it matches the filter in all keys (or maybe just in any one of them?) – xyldke May 25 '22 at 12:37
  • I think @ZAPE wants to filter items which include an object. If that please do like this. ```var exists = arr.find(function(o){ return Object.keys(o).some(function(k){ return !Object.keys(obj).indexOf(k)>-1 || o[k]!=obj1[k]; }); });``` – BTSM May 25 '22 at 12:39

1 Answers1

0
let newArray = arr.filter(a => a.age == obj.age);
Parsa S
  • 145
  • 5