Remove duplicates from JavaScript array

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Remove duplicates from JavaScript array

Post by JayBird »

Any idea how to remove duplicates?

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

Mark
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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 :)
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

thanks, but didn't need it in the end....will come in handy in the future tho

Ta
Post Reply