
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
Filtering Array of Objects in JavaScript
Suppose, we have two arrays of literals and objects respectively −
const source = [1, 2, 3 , 4 , 5]; const cities = [{ city: 4 }, { city: 6 }, { city: 8 }];
We are required to write a JavaScript function that takes in these two arrays. Our function should create a new array that contains all those elements from the array of objects whose value for "city" key is present in the array of literals.
Example
Let us write the code −
const source = [1, 2, 3 , 4 , 5]; const cities = [{ city: 4 }, { city: 6 }, { city: 8 }]; const filterByLiterals = (objArr, literalArr) => { const common = objArr.filter(el => { return literalArr.includes(el['city']); }); return common; }; console.log(filterByLiterals(cities, source));
Output
And the output in the console will be −
[ { city: 4 } ]
Advertisements