portfolio | contact
Sunday the 14th

remove duplicates from an array

Sunday, 7:11 PM
Ive been doing some really fun things with javascript lately, but not a lot of new ground worth posting about. I did however stumble upon a clever way removing duplicates from an array. I had a massive array which was 80% duplicates. The standard method which I had been using of two for loops - one nested in the other - was eating too many cycles. The solution was to exploit the map object - which does not allow duplicate keys.

Array.prototype.unique = function(){
var uniqueArray = [];
var workMap = {};

for(var i = 0; i < this.length; i++){workMap[this[i]] = 0}
for(x in workMap){uniqueArray.push(x)}

return uniqueArray;

This reduces the number of iterations from nn to n2 which is no small gain when dealing with large arrays!

◄ back