New Media Fun

Having fun in an online world

I was dealing with an array full of years (2009, 2009, 2010, 2010, 2009, 2010), and I wanted to easily remove duplicate entries in the array.

I found that jQuery had a .unique() function that removes duplicates. However, there if the duplicates are not in a sequential order, it will miss some of the items in the array.

var yearArray = new Array(2009, 2009, 2010, 2010, 2009, 2010);
$.unique(yearArray);

This returns 2009, 2010, 2009, 2010. The function missed a couple of the duplicates. This is simply fixed by sorting the array and then passing it into the unique function.

var yearArray = new Array(2009, 2009, 2010, 2010, 2009, 2010);
yearArray.sort();
$.unique(yearArray);

This should then return 2010, 2009. Hope this helps. :)

!! UPDATE !!
I hate Internet Explorer. I just discovered that the .unique() function works with DOM objects and because IE sucks, it doesn’t work properly. So, I had to replace the .unique() with the following code:

var yearArray = new Array(2009, 2009, 2010, 2010, 2009, 2010);
// still sort the array
yearArray.sort();

//$.unique(yearArray);

yearArray = uniqueArray(yearArray);


function uniqueArray(a){
    temp = new Array();
    for(var i = 0; i < a.length; i ++){
        if(!contains(temp, a[i])){
            temp.length+=1;
            temp[temp.length-1] = a[i];
        }
    }
    return temp;
}
function contains(a, e){
    for(j=0;j<a.length;j++)if(a[j]==e)return true;
    return false;
}

More code, but it works in all browsers now.

Thanks to Developer Snippets for the code

  1. Kyle Henderson Said,

    Thanks so much for this tip! Was banging my head against the wall with this one!

Add A Comment