Page 1 of 1

Remove duplicates from JavaScript array

Posted: Thu Jun 02, 2005 5:52 am
by JayBird
Any idea how to remove duplicates?

Im sure its easy, but kind find a reference anywhere.

Mark

Posted: Thu Jun 02, 2005 6:32 am
by Chris Corbyn
Maybe there's a method but I'm not aware of it so perhaps something like this. It'll support associative and numbered indexes.

Code: Select all

var sillyArray = new Array(
    'mr bump',
    'mr grumpy',
    'mr nosey',
    'mr silly',
    'mr funny',
    'mr nosey' //duplicate!
);

function arrayUnique(a) {
    y = new Array();
    for (x in a) {
        d = false; //d; a.k.a. duplicate
        for (i in y) {
            if (yїi] == aїx]) d = true;
        }
        if (!d) yїx] = aїx];
    }
    return y;
}
Although that was a bit rushed at work and for large arrays it might be a bit slow with those nested loops :)

Posted: Fri Jun 03, 2005 3:09 am
by JayBird
thanks, but didn't need it in the end....will come in handy in the future tho

Ta