Saturday, July 31, 2010

removing duplicates from an array

I searched online to look for a decent algorithm to remove duplicate values from array but didn't get any thing that was successful. There were couple but none of them worked if you had multiple no of duplicates.

The following algorithm works despite the no of duplicates in an array. This method works for me as I needed a sorted array...


_array.sort(); // shorts the array so that all the similar values are together

var firstWord:String; // variable for the first word
var secondWord:String; //variable for the second word
for(var j:int =0; j<= _array.length-1; j++)
{
firstWord = _array[j];
secondWord = _array[j+1]; //trace("f: " + firstWord + " S: " + secondWord);

if(firstWord == secondWord) //if the first word and second word is similar
{
_array.splice(j+1,1); // remove the second word from array
j--; // decrease value of counter to recheck for same word
}
}

No comments:

Post a Comment