Stephan Olsen Stephan Olsen - 1 month ago 8
Javascript Question

Removing duplicate objects from array

I'm trying to remove duplicate objects from an array. I've tried both using a set, and using a for loop. Why does neither of these solutions work?

var array = [
{"title": "Assistant"},
{"month": "July"},
{"event": "Holiday"},
{"title": "Assistant"}
];

var set = new Set(array);
console.log(set);

let newArray = [];
for(var i = 0; i < array.length; i++){
if(newArray.indexOf(array[i]) === -1){
newArray.push(array[i])
}
}
console.log(newArray);


jsfiddle: https://jsfiddle.net/7uzucqj5/

Answer Source

Change your code like this, Also works if you have same element in different order.

var arr = [
  {"title": "Assistant","name":"myname"},
  {"month": "July"},
  {"event": "Holiday"},
  {"name":"myname","title": "Assistant"}
];
var newArr = [];
var temp = [];
for(var i in arr){
  var str = JSON.stringify(sort(arr[i]));
  if(temp.indexOf(str)){
    temp.push(str);
    newArr.push(arr[i]);
  }
}

function sort(unordered){
const ordered = {};
Object.keys(unordered).sort().forEach(function(key) {
  ordered[key] = unordered[key];
});
return ordered;
}
console.log(newArr);