Fast Algorithm To Find Unique Items in JavaScript Array

September 6, 2009 · 22 comments   10,748 views

in Technical Publications

When I had the requirement to remove duplicate items from a very large array, I found out that the classic method to be not optimized as it took a pretty long time than desired. So, I devised this new algorithm that can sort a large array in a fraction of the original time.

The fastest method to find unique items in array

This method is kind of cheeky in its implementation. It uses the JavaScript’s object to add every item in the array as key. As we all know, objects accepts only unique keys and sure we did capitalize on that.

  1. Array.prototype.unique = function() {
  2.     var o = {}, i, l = this.length, r = [];
  3.     for(i=0; i<l;i+=1) o[this[i]] = this[i];
  4.     for(i in o) r.push(o[i]);
  5.     return r;
  6. };

Some Thoughts On This Algorithm

This is somewhat classified as "Hash Sieving" method and can also be related to a somewhat modified "Hash Sorting Algorithm" where every item in the array is a hash value and a hash function inserts item into a bucket, replacing existing values in case of hash collision. As such, this can be applied to any programming language for faster sieving of very large arrays.

This algorithm has a linear time complexity of O(2n) in worst case scenario. This is way better than what we will observe for the classic method as described below.

About the classic method

The classic (and most popular) method of finding unique items in an array runs two loops in a nested order to compare each element with rest of the elements. Consequently, the time complexity of the classic method to find the unique items in an array is around quadratic O(n²).

This is not a good thing when you have to find unique items within array of 10,000 items.

  1. Array.prototype.unique = function() {
  2.     var a = [], l = this.length;
  3.     for(var i=0; i<l; i++) {
  4.         for(var j=i+1; j<l; j++)
  5.             if (this[i] === this[j]) j = ++i;
  6.         a.push(this[i]);
  7.     }
  8.     return a;
  9. };

Comparing the above two algorithms

Test Data: An array of elements having N random integers.

Sample (N)Average CaseBest Case
ClassicNewClassicNew
500.430.250.010.02
1000.600.300.090.16
5009.570.870.10.2
100024.441.510.210.31
5000584.287.740.41.0
100002360.9015.030.71.8


Conclusion

This method of finding unique items within an array seems to be particularly useful for large arrays that are tending towards the real-life situations. When there are more items in an array that are similar, there is not much of a difference in performance and in fact, the classic algorithm scores better by a small margin. However, as the array gets more random, the runtime of the classic algorithm increases manifold.

Related posts:

  1. String Reversing Algorithm Performance In JavaScript
  2. Transpose An Array In JavaScript and jQuery
  3. Convert FusionCharts Data-XML To JavaScript Array
  4. JavaScript Optimization – Destructive Vs Indexed Array Iteration
  5. Generating Pareto Chart Data for FusionCharts
  • Andy L

    You work wonders at times. This is such a simple trick and yet so effective. Perhaps no one thinks about performance and perfection of algorithms as much as you do!
    By the way, in line 3 of your Hash Seiving algorithm, why did you do o[this[i]] = this[i];?

  • http://www.shamasis.net/ Shamasis Bhattacharya

    Do not flatter me that much! :P

    o[this[i]] = this[i]; preserves the data-type of the items within the JavScript array. This is because JavaScript object keys are always string and we would not want to needlessly convert a numeric array to string array! By the way, if you are not bothered about the data-type of the unique array, then you can use a modified version of the algorithm that always returns string data-type and is faster due to lesser overhead.

    Array.prototype.strUnique = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l;i++) o[this[i]] = null;
    for(i in o) r.push(i);
    return r;
    };

  • http://www.javascriptbank.com/ JavascriptBank

    Very cool & good tip, thank you very much for sharing.
    Can I share this snippet on my http://www.javascriptbank.com/

    Awaiting your response. Thanks

  • http://www.shamasis.net/ Shamasis Bhattacharya

    Sure. Sharing is caring! Care back for me by retaining my link and attribution. :)

  • Kevin N

    I’m trying to use this (the modified string data-type only function) inside an embedded js tool (i believe it uses rhino) and I’m having difficulty.  Instead of removing the duplicates  I want to append  1, 2, 3…n at the end of the duplicative strings  (space then integer so Kevin,Kevin becomes  Kevin,Kevin 1). I’m new to js in general and not sure i’m creating the array correctly – I may ask some stupid questions.
    var urlarray = new Array(URLName.getString());
    should that work? – as I understand it from there I can call this function using the array?

  • Nilton

    reverse for loops are faster for spidermonkey.
    As for Kevin’s question:
    Array.prototype.toUnique = function() {
    var o = {}, i, l = this.length, r = []; n = []; modified=0;
    for(i=this.length-1; i>=0;–i){
    if(n[this[i]]){
    modified=1;
    o[this[i]+” “+ n[this[i]]] = this[i]+ n[this[i]]++;
    }else{
    o[this[i]] = this[i];n[this[i]]=1
    }
    }
    if(!modified)return this;
    for(i in o) r.push(o[i]);
    return r;
    };

  • http://www.shamasis.net/ Shamasis Bhattacharya

    Kevin,

    For your use of prefixing the duplicates within a JavaScript Array with number, the following code would be useful:

    Array.prototype.markDuplicates = function() {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l; i += 1) {
    if(o[this[i]] >= 0) {
    o[this[i]] += 1;
    r.push(this[i] + ' ' + o[this[i]]);
    }
    else {
    o[this[i]] = 0;
    r.push(this[i]);
    }
    }
    return r;
    };

    // Usage would look like
    var myArr = ['Kevin', 'Kevin', 'Shamasis', 'Kevin'],
    newArr = myArr.markDuplicates();

  • http://www.shamasis.net/ Shamasis Bhattacharya

    I did not want to do a reverse so as to maintain the original order.

  • http://joshuakalis.com Joshua Kalis

    I don’t like augmenting the default types much, so I just made a function.

    function (ar) {
    var f = {},
    i = 0,
    l = ar.length,
    r = [];
    while (i < l) {
    !f[ar[i]] && r.push(ar[i]);
    f[ar[i++]] = 1;
    }
    return r;
    };

    I have it as a method on a properly name-spaced object and use like this:

    var result = Utils.array.unique(array_name);

  • Trav

    Hi,

    warning… js novice.

    I have a js array with 50,000 objects in it.  I need to find unique object fields in the array.

    eg.

    var data = [{name: 'tom',age:12},{name:'sam',age:13},{name:'tom',age:20}];

    so i need to find unique base on object field like:

    var return = data.unique(‘name’);

    so return would now have:

    return = [{name: 'tom'},{name:'sam'}];

    I have this working using jquery.inArray but it is very slow with large data sets.

    Can you help me?

  • Nemoniccom

    I’m not so sure this is the best method. What about doing the following:

    Array.prototype.unique = function(){
    Var Len = this.length,
    Elems = [],
    Elemslen = 0′
    Table ={},
    I;
    For(I=0;I+<Len;I++){
    If(!Table[I]){
    Table[I] = 1;
    This[Elemslen++] = This[I];

    }
    }

    This.length = Elemslen;
    }

  • http://www.spencernetdevelopment.com/ Neumoniccom

    Sorry,  I tried to type this originally on an Ipad.  What a pain!  The code should be as follows:

    Array.prototype.unique = function(){
    var len = this.length,
    elems = [],
    elemsLen = 0,
    table ={},
    i;
    for(i=0;i<len;i++){
    if(!table[this[i]]){
    table[this[i]] = 1;
    this[elemsLen++] = this[i];
    }
    }

    this.length = elemsLen;
    return this;
    }

  • Izayoi400

    what i use:

    var arr1=[1,2,3,2,5,1,2,1,2,3,6,1,2,1,2,3]
    var blah=”"for(each1 in arr1) { if(blah.search(arr1[each1]) == -1 )  {  blah=blah+arr1[each1]  } }
    alert(blah)var newblah = blah.split(“”)alert(newblah)

  • Izayoi400

    sorry hopefully this will be formatted better…

    var arr1=[1,2,3,2,5,1,2,1,2,3,6,1,2,1,2,3]var blah=”"for(each1 in arr1){if(blah.search(arr1[each1]) == -1 ){blah=blah+arr1[each1]}}alert(blah)var newblah = blah.split(“”)alert(newblah)

  • http://www.spencernetdevelopment.com/ Neumoniccom

    This isn’t a very good method.  You should never use the for in loop for arrays.  That loop should only be used on objects where the number of properties / methods isn’t known ( idea taken from Nicolas C. Zakas’ Book “High Performance Javascript” p 62 – 63).  You decrease performance using the for-in loop because you have to access all the properties / members of the object and it’s prototype chain.

    Also note that using multiple object methods (IE split , search, etc.) will lead to performance degradation.This is what I was originally trying to post.  For string and numeric values I believe it is the most straight forward:By using the below prototype method you can call unique on any array object like this:var a = [4,5,4,3,45,3,12,1,234,5,4,3,2,1];a.unique();Here is the prototype method for the Array object:Array.prototype.unique = function(){  var len = this.length,         elems = [],         elemsLen = 0,         table ={},         i;  for(i=0;i<len;i++){    if(!table[this[i]]){      table[this[i]] = 1;      this[elemsLen++] = this[i];    }  }  this.length = elemsLen;  return this;}

  • http://robinjakobsson.se/blog/2011/08/19/fast-algorithm-to-find-unique-items-in-javascript-array/ Fast Algorithm To Find Unique Items in JavaScript Array | Robin Jakobsson

    [...] Fast Algo­rithm To Find Unique Items in JavaScript Array. via @LeaVerou This entry was posted in Web development and tagged algorithm, javascript by Robin. Bookmark the permalink. /* [...]

  • http://twitter.com/vikasrao vikasrao

    I had the same need and came up with this solution a while ago, good to know it actually has a name :-) : http://vikasrao.wordpress.com/2011/06/09/removing-duplicates-from-a-javascript-object-array/

  • Msitchen

    This should be done with a hash table for O(n) 

  • Gregor

    Thanks for teaching me the term “Hash Sieving” I’ve been using this trick for 15 years but didn’t know it had a name.

  • http://www.shamasis.net/ Shamasis Bhattacharya

    You are right, we have used this technique for centuries now! However, for JS it is performance enhancing unlike many other languages. The overhead of dictionaries and other similar structures in many languages are comparatively higher.

    Agree?

  • Relic

    Then ya just need to use .unshift() instead of .push()…. problem solved!

  • Brandon Benvie

    Array.prototype.unique = function(){
    return this.filter(function(s, i, a){ return i == a.lastIndexOf(s); });
    }

    You loop through the array at most an average of 50% of the length of the array per item, when there’s zero doubles. The more items filtered the more efficient it is. Usually doesn’t beat the hash method but it has its place. It wins on style points though cause sometimes looking pretty is better than being smart.