Was it helpful?

Question

Retrieve user id from array of object - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects where the user names are mapped to some unique ids like this −

const arr = [
   {"4": "Rahul"},
   {"7": "Vikram"},
   {"6": "Rahul"},
   {"3": "Aakash"},
   {"5": "Vikram"}
];

As apparent in the array, same names can have more than one ids but same ids can be used to map two different names.

We are required to write a JavaScript function that takes in one such array as the first argument and a name string as the second argument. The function should return an array of all ids that were used to map the name provided as second argument.

Example

Following is the code −

const arr = [
   {"4": "Rahul"},
   {"7": "Vikram"},
   {"6": "Rahul"},
   {"3": "Aakash"},
   {"5": "Vikram"}
];
const name = 'Vikram';
const findUserId = (arr, name) => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      const key = Object.keys(arr[i])[0];
      if(arr[i][key] !== name){
         continue;
      };
      res.push(key);
   };
   return res;
};
console.log(findUserId(arr, name));

Output

This will produce the following output in console −

['7', '5']
raja
Published on 30-Sep-2020 17:14:49
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top