In this tutorial, you’ll learn how to find duplicate objects in an array using JavaScript. You already learnt how to find duplicate values in an array using JavaScript in one of our earlier posts. You’ll be following a similar approach to find duplicate objects in an array.

How To Find Duplicate Objects In An Array

You’ll be keeping two empty arrays, one for unique items and another for duplicate items. You’ll iterate over the given objects array and check if the unique items array contains the iterated object. If found you’ll push that to the duplicate array else push it to unique array list. And at the end you’ll have an array of unique objects and duplicate objects.

Implementing The Logic To Find Duplicate

Here is how the code looks like :

let objList = [{
  "id" : 5,
  "name" : "June"
},{
  "id" : 4,
  "name" : "Jane"
},{
  "id" : 3,
  "name" : "Julia"
},{
  "id" : 2,
  "name" : "Nancy"
},{
  "id" : 5,
  "name" : "June"
},{
  "id" : 5,
  "name" : "June"
}];

let uniqueList = [];
let dupList = [];

Array.prototype.contains = function(item){
  let filtered_item = this.filter((i) => {
    return i.id === item.id
  });
  return !!filtered_item.length;
}

function contains(list, item){
  let filtered_item = list.filter((i) => {
    return i.id === item.id
  });
  return !!filtered_item.length;
}

function pushToUniqueList(item){
  if(!uniqueList.contains(item)) uniqueList.push(item);
}

function pushToDuplicateList(item){
  if(!dupList.contains(item)) dupList.push(item);
}

for(let i = 0; i < objList.length; i++){
  if(uniqueList.contains(objList[i])){
    pushToDuplicateList(objList[i]);
  } else {
    pushToUniqueList(objList[i]);
  }
}

console.log('Duplicate list is ', dupList);
console.log('Unique list is ', uniqueList);

objList is the given array of objects. We are iterating over object array and checking if uniqueList contains the iterated object. If it contains the object, push to the duplicate list else push it to unique list.

Wrapping It Up

In this tutorial, you learnt how to find duplicate objects in an array using JavaScript. Have you ever encountered a similar situation ? Did you use any other approach to remove duplicate objects ? Do let us know in the comments below.