Remove duplicate objects from an array using javascript

I see, the problem there is that the complexity is squared. There is one trick to do it, it’s simply by using “Associative arrays”.

You can get the array, loop over it, and add the value of the array as a key to the associative array. Since it doesn’t allow duplicated keys, you will automatically get rid of the duplicates.

Since you are looking for title and artist when comparing, you can actually try to use something like:

var arrResult = {};
for (i = 0, n = arr.length; i < n; i++) {
    var item = arr[i];
    arrResult[ item.title + " - " + item.artist ] = item;
}

Then you just loop the arrResult again, and recreate the array.

var i = 0;
var nonDuplicatedArray = [];    
for(var item in arrResult) {
    nonDuplicatedArray[i++] = arrResult[item];
}

Updated to include Paul’s comment. Thanks!

Leave a Comment