I am working with an array of mongodb's ObjectID objects. I must check if this array contains duplicates, and if so, remove them.
Here is the removeDuplicate function I have, which simply loops over an array with two indexes. If two objects are identical, then the splice() function will remove one of them.
function removeDuplicates(array) {
var a = array.concat(); // Copy object
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
console.log(a[i] + " vs " + a[j]);
if(a[i].equals(a[j]))
console.log("removed : " + a.splice(j--, 1));
}
}
return a;
}
Let's say I have a simple array with two identical ObjectID objects in it.
Then I call the removeDuplicates function, passing the array.
Finally, I print out the array itself.
var array = [];
array.push(new ObjectID("56fc227026aed8e74a699b20"));
array.push(new ObjectID("56fc227026aed8e74a699b20"));
removeDuplicates(array);
console.log(array);
Here is the output. As you can see, nothing is removed at the end.
56fc227026aed8e74a699b20 vs 56fc227026aed8e74a699b20
removed : 56fc227026aed8e74a699b20
[ 56fc227026aed8e74a699b20, 56fc227026aed8e74a699b20 ]
What am I doing wrong ?