How do I remove duplicate values from an array in as3? Say if I have an array=[1,1,2,2,4,5] I would like to have the result as array=[1,2,4,5]
5 Answers
Another option is using hash map/Dictionary like so:
import flash.utils.Dictionary;
var a:Array = ["Tom", "John", "Susan", "Marie", "Tom", "John", "Tom", "Eva"];
var b:Dictionary = new Dictionary(true);//has map/cannot have duplicate keys
var c:Array = [];//filtered/unique entries array
for(var i:int = 0; i < a.length; i++) b[a[i]] = i;//hash array entries
for(var key:String in b) c.push(key);//put them back into an array
b = null;//clear/release the hash map
trace(c);//traces: Tom Eva John Susan Marie
1 Comment
ashok_khuman
Thanks for suggestion to use Dictionary class.
var a:Array = ["Tom", "John", "Susan", "Marie", "Tom", "John", "Tom", "Eva"];
a.sort();
var i:int = 0;
while(i < a.length) {
while(i < a.length+1 && a[i] == a[i+1]) {
a.splice(i, 1);
}
i++;
}
As can be seen here
Comments
Try something like:
var array:Array = [1,1,2,2,4,5];
trace(array);
trace(removeDuplicates(array));
function removeDuplicates(inArray:Array):Array
{
return inArray.filter(removeDuplicatesFilter);
}
function removeDuplicatesFilter(e:*, i:int, inArray:Array):Boolean
{
return (i == 0) ? true : inArray.lastIndexOf(e, i - 1) == -1;
}
Also, I recommend you to create a class, and implement those as static methods, something like.
public class ArrayUtils
{
public static function removeDuplicates(inArray:Array):Array
{
return inArray.filter(_removeDuplicatesFilter);
}
protected static function _removeDuplicatesFilter(e:*, i:int, inArray:Array):Boolean
{
return (i == 0) ? true : inArray.lastIndexOf(e, i - 1) == -1;
}
}
Also use like:
var array:Array = [1,1,2,2,4,5];
trace(ArrayUtils.removeDuplicates(array));
2 Comments
ashok_khuman
Thanks this looks concise rather than using any Dictionary classes.
gabriel
@ashok_khuman You are very welcome! Hope was possible to help somehow.
Use Underscore.as!
https://github.com/amacdougall/underscore.as
import com.amacdougall.underscore.*;
_.uniq([1,1,2,2,4,5);
// 1,2,4,5
Comments
private function removeDuplicatesInCollection(collection:ArrayCollection):Array{
var dic:Dictionary = new Dictionary();
for each (var item:MyObject in collection){
var key: Object = new Object();
key.network = item.network;
key.day = item.day;
key.date = item.date;
key.time =item.time;
key.cost = item.cost;
dic[JSON.stringify(key)] = item ;
}
return DictionaryUtil.getValues(dic) ;
}