
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Match Between 2 Arrays in JavaScript
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 ]
Advertisements