- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search from an array of objects via array of string to get array of objects in JavaScript
Suppose, we have one array of strings and another array of objects like this −
const arr1 = [ '1956888670', '2109171907', '298845084' ]; const arr2 = [ { KEY: '1262875245', VALUE: 'Vijay Kumar Verma' }, { KEY: '1956888670', VALUE: 'Sivakesava Nallam' }, { KEY: '2109171907', VALUE: 'udm analyst' }, { KEY: '298845084', VALUE: 'Mukesh Nagora' }, { KEY: '2007285563', VALUE: 'Yang Liu' }, { KEY: '1976156380', VALUE: 'Imtiaz Zafar' }, ];
We are required to write a JavaScript function that takes in two such arrays. Then our function should return a filtered version of the second array that contains only those objects whose "KEY" property is listed in the first array as a string.
Example
The code for this will be −
const arr1 = [ '1956888670', '2109171907', '298845084' ]; const arr2 = [ { KEY: '1262875245', VALUE: 'Vijay Kumar Verma' }, { KEY: '1956888670', VALUE: 'Sivakesava Nallam' }, { KEY: '2109171907', VALUE: 'udm analyst' }, { KEY: '298845084', VALUE: 'Mukesh Nagora' }, { KEY: '2007285563', VALUE: 'Yang Liu' }, { KEY: '1976156380', VALUE: 'Imtiaz Zafar' }, ]; const filterByKey = (arr1 = [], arr2 = []) => { let res = []; res = arr2.filter(el => { const { KEY } = el; const index = arr1.indexOf(KEY); return index !== -1; }); return res; }; console.log(filterByKey(arr1, arr2));
Output
And the output in the console will be −
[ { KEY: '1956888670', VALUE: 'Sivakesava Nallam' }, { KEY: '2109171907', VALUE: 'udm analyst' }, { KEY: '298845084', VALUE: 'Mukesh Nagora' } ]
- Related Articles
- Creating an array of objects based on another array of objects JavaScript
- Converting array of objects to an object of objects in JavaScript
- Sorting an array of objects by an array JavaScript
- Extract unique objects by attribute from an array of objects in JavaScript
- Array of objects to array of arrays in JavaScript
- Can we search an array of objects in MongoDB?
- Manipulating objects in array of objects in JavaScript
- Get only specific values in an array of objects in JavaScript?
- Compare array of objects - JavaScript
- JavaScript - length of array objects
- Converting array of objects to an object in JavaScript
- Convert string with separator to array of objects in JavaScript
- Search array of objects in a MongoDB collection?
- Using methods of array on array of JavaScript objects?
- Filtering array of objects in JavaScript

Advertisements