- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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' } ]
Advertisements