Remove duplicates and map an array in JavaScript


Suppose, we have an array of objects like this −

const arr = [
   {id:123, value:"value1", name:"Name1"},
   {id:124, value:"value2", name:"Name1"},
   {id:125, value:"value3", name:"Name2"},
   {id:126, value:"value4", name:"Name2"}
];

Note that some of the "name" property in objects within the array are duplicate.

We are required to write a JavaScript function that takes in one such array of objects. The function should then construct a new array of strings that contains only unique "name" property value from the array.

Therefore, the output for the above input should look like this −

const output = ["Name1", "Name2"];

Example

The code for this will be −

const arr = [
   {id:123, value:"value1", name:"Name1"},
   {id:124, value:"value2", name:"Name1"},
   {id:125, value:"value3", name:"Name2"},
   {id:126, value:"value4", name:"Name2"}
];
const pickNames = (arr = []) =>{
   const res = [];
   for (let i = arr.length; i−−;){
      if (res.indexOf(arr[i].name) < 0) {
         res.push(arr[i].name);
      };
   }
   return res;
};
console.log(pickNames(arr));

Output

And the output in the console will be −

[ 'Name2', 'Name1' ]

Updated on: 20-Nov-2020

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements