Search from Array of Objects via Array of Strings 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