Was it helpful?

Question

Remove array duplicates by property - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}, {name: "Jack", age: "21"}];

We are required to write a JavaScript function that takes in one such array and removes all the objects that have duplicate values for the name.

Therefore, for the above array, the output should be −

const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}];

Example

Following is the code −

const arr = [
   {name: "Jack", age: "14"},
   {name: "bob", age: "14"},
   {name: "sue", age: "21"},
   {name: "Jill", age: "16"},
   {name: "Jack", age: "21"}
];
const removeDuplicate = arr => {
   const appeared = {};
   for(let i = 0; i < arr.length; ){
      if(!appeared.hasOwnProperty(arr[i].name)){
         appeared[arr[i].name] = 1;
         i++;
         continue;
      };
      arr.splice(i, 1);
   };
};
removeDuplicate(arr);
console.log(arr);

Output

This will produce the following output in console −

[
   { name: 'Jack', age: '14' },
   { name: 'bob', age: '14' },
   { name: 'sue', age: '21' },
   { name: 'Jill', age: '16' }
]
raja
Published on 30-Sep-2020 16:53:13
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top