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' }
]

Updated on: 23-Nov-2020

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements