Today I was working in actionscript 3 + php project. I was working in an array and I needed to remove duplicate entries from array. In php its very easy to remove duplicate entries.
There is a function in php named array_unique($array); that removes duplicate elements from array. So in php I could easily use
$arr = array('a', 'b', 'a', 'c', 'd', 'b');
$arr = array_unique($arr); //removes duplicate entries
But there is no such type of built in function in actionscript 3 for array. So I created my own function and used it
function removeDuplicate(arr:Array) : void{
var i:int;
var j: int;
for (i = 0; i < arr.length - 1; i++){
for (j = i + 1; j < arr.length; j++){
if (arr[i] === arr[j]){
arr.splice(j, 1);
}
}
}
}
Now just call the function and pass an array
var arr:Array = new Array("a", "b", "a", "c", "d", "b");
removeDuplicate(arr);
splice(startIndex:int, deleteCount:uint); method removes elements from an array. So using 2 simple loops I solved my problem. But as my arrays are short 20 elements max so I don’t need to optimize this function.
reference: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html







I believe the 2nd loop needs to sequence from the end to i+1. The problem is that the item at j is removed, then j is incremented – skipping a record
try
05: for (j = arr.length – 1; j > i; j–) {
I need like this… but I m doing something wrong in this :- please check once and let me know solution if you know….
var mainArr:Array = ["cat","dog","chocolate","fire","food","house","market","butter",
"fruit","ham","computer","door","hen"]
// c,d,f,m,b,h = 6
removeDuplicate(mainArr);
function removeDuplicate(arr:Array) : void{
var i:int;
var j: int;
for (i = 0; i < arr.length; i++){
for (j = i + 1; j < arr.length; j++){
if (arr[i].substr(0,1) == arr[j].substr(0,1)){
arr.splice(j,1);
}
}
}
trace(arr)
trace(arr.length)
}
A much more elegant solution:
arr.filter(function(e:*, i:int, a:Array):Boolean {return a.indexOf(e) == i;});
source: http://www.razorberry.com/blog/archives/2008/09/03/as3-removing-duplicates-from-an-array/