Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove duplicates in Array 1

Status
Not open for further replies.

NewTerminator

Programmer
Apr 28, 2003
22
IN
Anyone know how to remove duplicate values from an array using actionscript. Any help would be appreciated. Thanks..


NewTerminator
 
Array.prototype.unique=function(){
for(var y=0;y<this.length;++y){
var ty = this[y];
for(var z=(y+1);z<this.length;++z){
while(ty==this[z]){
this.splice(z,1)
}
}
}
return this
}
my_arr = [1,2,3,3,2,1,4]
_arr2 = my_arr.unique()
trace(_arr2)
//returns 1,2,3,4
 
Code:
removeDuplicates = function (checkArray) {
	for (var i = 0; i<checkArray.length; i++) {
		var k = i+1;
		for (var j = k; j<checkArray.length; j++) {
			if (checkArray[i] == checkArray[j]) {
				checkArray.splice(j, 1);
			}
		}
	}
	return checkArray;
};
myArray = [1, 2, 3, 4, 5, 6, 7, 5, 4, 8, 9, 2, 3, 4, 1, 8, 9];
trace(&quot;before &quot;+myArray);
myNewArray = removeDuplicates(myArray);
trace(&quot;after &quot;+myNewArray);
//
stop();
 
Or...

Code:
aNumberList = new Array(1,2,3,4,5,5,2,1,4,3);
aNewArray = new Array();

for(i=0;i<aNumberList.length;i++){
	bExists = false;
	for(j=0;j<aNewArray.length;j++){
		if(aNumberList[i] == aNewArray[j]){
			bExists = true;
		}
	}
	if(!bExists){
	aNewArray[aNewArray.length] = aNumberList[i];
	}
}

trace(aNewArray);
[code]

Regards,

[img]http://members.lamicro.com/~FGill/cubalibre2.gif[/img]
 
The 2 loops take a long time if the array size is huge (in my case it cross over 35,000) values. I found a javascript code that can do the trick using hash algorithm. Thought i would share it with u guys :)

function removeDuplicates_list()
{
var mainlist = document.form1.mainlist.value; //This refers to a text area box
mainlist = mainlist.replace(/\r/gi, &quot;\n&quot;);
mainlist = mainlist.replace(/\n+/gi, &quot;\n&quot;);

var listvalues = new Array();
var newlist = new Array();

listvalues = mainlist.split(&quot;\n&quot;);

var hash = new Object();

for (var i=0; i<listvalues.length; i++)
{
if (hash[listvalues.toLowerCase()] != 1)
{
newlist = newlist.concat(listvalues);
hash[listvalues.toLowerCase()] = 1
}
}
document.form1.mainlist.value = newlist.join(&quot;\r\n&quot;);
}

Regards,

Me
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top