

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Questions & Answers
- 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
- Array of objects to array of arrays in JavaScript
- Manipulating objects in array of objects in JavaScript
- JavaScript - length of array objects
- Compare array of objects - JavaScript
- Can we search an array of objects in MongoDB?
- Using methods of array on array of JavaScript objects?
- Filtering array of objects in JavaScript
- Combine array of objects in JavaScript
- Filter JavaScript array of objects with another array
- Search array of objects in a MongoDB collection?
- Remove duplicates from a array of objects JavaScript
- Converting array of objects to an object in JavaScript
Advertisements