Filter JavaScript Array of Objects with Another Array
Suppose, we have an array of objects like this −
const arr = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ];
We are required to write a JavaScript function that takes in one such array as the first argument and an array of string literals as the second argument.
Our function should then filter the input array of objects to contain only those objects whose "area" property is included in the array of literals (second argument).
Example
The code for this will be −
const arr = [ {area: 'NY', name: 'Bla', ads: true}, {area: 'DF', name: 'SFS', ads: false}, {area: 'TT', name: 'SDSD', ads: true}, {area: 'SD', name: 'Engine', ads: false}, {area: 'NSK', name: 'Toyota', ads: false}, ]; const keys = ['NY', 'SD']; const filterByArea = (arr = [], keys = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const { area } = arr[i]; if(keys.includes(area)){ res.push(arr[i]); }; }; return res; }; console.log(filterByArea(arr, keys));
Output
And the output in the console will be −
[ { area: 'NY', name: 'Bla', ads: true }, { area: 'SD', name: 'Engine', ads: false } ]
Advertisements