
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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