Thursday, May 8, 2008

@Unique in Javascript

Update, 16.06.09: As Ronaldo points out, this doesn't work in IE6, as it doesn't have the Array.indexOf-method (I probably tested the function in a Prototype JS-enviroment). To make the function work for browsers that doesn't have the aforementioned method:
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for( var i = 0, len = this.length; i < len; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}




function arrayUnique( array ){
var uniqueArray = [];

var item;
for( var i = 0, len=array.length ; i < len ; i++ ){
item = array[i];
if( uniqueArray.indexOf( item ) == -1 ){
uniqueArray.push( item );
}
}

return uniqueArray;
}



Tested in IE6/FF2

2 comments:

Unknown said...

Tommy,

I tested this in IE 6, but does not work. Occours an error in this line

if( uniqueArray.indexOf( item ) == -1 ),

in IE is needed a some change to works ?

In Mozilla Firefox runs all ok, only IE what a have problem


I put this code in a button on single notes form

var List_1= new Array(4);
List_1[0] = "Luis";
List_1[1] = "Paula";
List_1[2] = "Luis";
List_1[3] = "Marcos";
List_1[4] = "Jorge";

alert ('result = ' +arrayUnique(List_1));

and the your function

function arrayUnique( array ){
var uniqueArray = [];

var item;
for( var i = 0, len=array.length ; i < len ; i++ ){
item = array[i];
if( uniqueArray.indexOf( item ) == -1 ){
uniqueArray.push( item );
}
}

return uniqueArray;
}

on JS Header on this same form

Tommy Valand said...

Thanks for letting me know. I updated the original post with a workaround for browsers that doesn't have the Array.indexOf-method.