apache-flex 如何删除数组flex中的重复值?

ghhaqwfi  于 2022-11-01  发布在  Apache
关注(0)|答案(5)|浏览(179)

如何在as3中删除数组中的重复值?假设我有一个array=[1,1,2,2,4,5],我希望得到结果array=[1,2,4,5]

y1aodyip

y1aodyip1#

另一个选择是使用散列Map/Dictionary,如下所示:

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
vaj7vani

vaj7vani2#

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++;
}

可以看出here

sh7euo9m

sh7euo9m3#

请尝试以下内容:

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;
     }

此外,我建议您创建一个类,并将其实现为静态方法,类似于。

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; 
            }
       }

也用像:

var array:Array = [1,1,2,2,4,5];
        trace(ArrayUtils.removeDuplicates(array));
ghg1uchk

ghg1uchk4#

请使用Underscore.as!
https://github.com/amacdougall/underscore.as

import com.amacdougall.underscore.*;
_.uniq([1,1,2,2,4,5);
// 1,2,4,5
avwztpqn

avwztpqn5#

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) ;
    }

相关问题