all groups > flash actionscript > september 2004 >
You're in the

flash actionscript

group:

Isolating unique elements in an Array?


Isolating unique elements in an Array? tweekerbythespeaker
9/20/2004 9:51:58 PM
flash actionscript: I am trying to output a number of unique elements in an array. For instance, If
I had the array:

colors=["0x000000","0xFF0000","0xFF0000","0xFFFFFF","0xFFFFFF"];

I want to run a function on the above array that spits out the number "3".
There are 5 indexs in there, but only 3 UNIQUE values.

Any ideas? I am stumped....!!!! any help would be appreciated. Thanks !

joe
Re: Isolating unique elements in an Array? tweekerbythespeaker
9/20/2004 10:14:50 PM
Just found this... It works, kinda...
UNLESS you add the same value more than a few times. For example, if you add
"banana" to the array a few more times, it doesnt give an array of truly unique
elements. In essence, it doesn't work at all, BUT.... it seems to be trying to
do what I want, so I figured someone would be able to elaborate on this.

Array.prototype.unique=function(){
for(var y=0;y<this.length;++y){
for(var z=(y+1);z<=this.length;++z){
if(this[y]==this[z]){
this.splice(z,1)
}
}
}
trace(this);
}



_root.myarray=new Array("apple","pear","orange","banana","apple")
_root.myarray.unique();
Re: Isolating unique elements in an Array? mandingo
9/20/2004 10:24:59 PM
here, work with this...


colors=["0x000000","0xFF0000","0xFF0000","0xFFFFFF","0xFFFFFF","0x000000","0xFF0
000","0xFF0000","0xFFFFFF","0xFFFFFF","0x000000","0xFF0000","0xFF0000","0xFFFFFF
","0xFFFFFF"];
uniqueArray = new Array();

for(var k=0; k<colors.length; k++){
var increment = 0;
for(var j=0; j<uniqueArray.length; j++){
if(colors[k] == uniqueArray[j]){
increment ++;
}
}
if(increment == 0){
uniqueArray.push(colors[k]);
}
}

You will notice that it doesn't matter how many elements, only the unique
values get pushed to the uniqueArray

I hope that helps,
cheers,
AddThis Social Bookmark Button