JavaScript Match between 2 arrays

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have two arrays, one of String literals and another of objects.

const data = [{
   name: 'Kamlesh Kapasi',
   uid: 123
}, {
      name: 'Mahesh Babu',
      uid: 129
}, {
      name: 'Akshay Kapoor',
      uid: 223
}, {
      name: 'Vikas Gupta',
      uid: 423
}, {
      name: 'Mohit Dalal',
      uid: 133
}, {
      name: 'Rajkumar Hirani',
      uid: 233
}, {
      name: 'Joy',
      uid: 127
}];
const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu',
'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta']

Our job is to write a function that iterates over the names array and constructs an array of Numbers that contains uid of specific names in the same order as they appear in the names array.

Let’s write the code for this function −

Example

const data = [{
   name: 'Kamlesh Kapasi',
   uid: 123
}, {
      name: 'Mahesh Babu',
      uid: 129
}, {
      name: 'Akshay Kapoor',
      uid: 223
}, {
      name: 'Vikas Gupta',
      uid: 423
}, {
      name: 'Mohit Dalal',
      uid: 133
}, {
      name: 'Rajkumar Hirani',
      uid: 233
}, {
      name: 'Joy',
      uid: 127
}];
const names = ['Joy', 'Rajkumar Hirani', 'Akshay Kapoor', 'Mahesh Babu',
'Mohit Dalal', 'Kamlesh Kapasi', 'Vikas Gupta']
const mapId = (arr, names) => {
   return names.reduce((acc, val) => {
      const index = arr.findIndex(el => el.name === val);
      return acc.concat(arr[index].uid);
   }, []);
}
console.log(mapId(data, names));

Output

The output in the console will be −

[
   127, 233, 223,
   129, 133, 123,
   423
]
raja
Published on 24-Aug-2020 12:59:35
Advertisements