Thursday, November 29, 2018

How to remove duplicate objects from an array in javascript

This tutorial explains how to remove duplicate objects from an array in javascript. Lets see the below example to build more understanding on this and hoping that may solve your future coding problems. We are using ES6 map and filter methods to remove the duplicate objects from an array.

How to remove duplicate objects from an array in javascript

Remove duplicate objects from an array :

Lets consider we are having below array of objects with the id and name.

const arr = [
  { id: 2, name: "sumit" },
  { id: 1, name: "amit" },
  { id: 3, name: "rahul" },
  { id: 4, name: "jay" },
  { id: 2, name: "ra one" },
  { id: 3, name: "alex" },
  { id: 1, name: "devid" },
  { id: 7, name: "sam" },
  ];

 we are using below chain functions to filter out unique array value and remove duplicate objects from an array in javascript,

function getUnique(arr, index) {

  const unique = arr
       .map(e => e[index])

       // store the keys of the unique objects
       .map((e, i, final) => final.indexOf(e) === i && i)
  
       // eliminate the dead keys & store unique objects
      .filter(e => arr[e]).map(e => arr[e]);      

   return unique;
}

console.log(getUnique(arr,'id'))

After implementation we will get below output :

> Array 
[Object { id: 2, name: "sumit" }, 
Object { id: 1, name: "amit" }, 
Object { id: 3, name: "rahul" }, 
Object { id: 4, name: "jay" }, 
Object { id: 7, name: "sam" }]

This is all about removing duplicate objects from an array in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment