我有一个非常简单的JavaScript数组,可能包含也可能不包含重复项。

var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];

我需要删除重复项并将唯一值放入新数组。

我可以指出我尝试过的所有代码,但我认为它们没有用,因为它们不起作用。我也接受jQuery解决方案。

类似的问题:

获取数组中的所有非唯一值(即:重复/多次出现)


当前回答

复杂度为O(n)的Vanilla JS解决方案(对于这个问题最快)。如果需要,修改hashFunction以区分对象(例如1和“1”)。第一种解决方案避免了隐藏循环(在Array提供的函数中常见)。

var dedupe = function(a) 
{
    var hash={},ret=[];
    var hashFunction = function(v) { return ""+v; };
    var collect = function(h)
    {
        if(hash.hasOwnProperty(hashFunction(h)) == false) // O(1)
        {
            hash[hashFunction(h)]=1;
            ret.push(h); // should be O(1) for Arrays
            return;
        }
    };

    for(var i=0; i<a.length; i++) // this is a loop: O(n)
        collect(a[i]);
    //OR: a.forEach(collect); // this is a loop: O(n)

    return ret;
}

var dedupe = function(a) 
{
    var hash={};
    var isdupe = function(h)
    {
        if(hash.hasOwnProperty(h) == false) // O(1)
        {
            hash[h]=1;
            return true;
        }

        return false;
    };

    return a.filter(isdupe); // this is a loop: O(n)
}

其他回答

另一种不用编写太多代码就可以做到这一点的方法是使用ES5 Object.keys-method:

var arrayWithDuplicates = ['a','b','c','d','a','c'],
    deduper = {};
arrayWithDuplicates.forEach(function (item) {
    deduper[item] = null;
});
var dedupedArray = Object.keys(deduper); // ["a", "b", "c", "d"]

在函数中提取

function removeDuplicates (arr) {
    var deduper = {}
    arr.forEach(function (item) {
        deduper[item] = null;
    });
    return Object.keys(deduper);
}

我知道我有点晚了,但这里有另一个使用jinqJ的选项

参见Fiddle

var result = jinqJs().from(["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"]).distinct().select();

使用reduce和find的方法。

常量=[1,1,2,3,4,4];函数唯一(数组){return array.reduce((a,b)=>{让isIn=a.find(元素=>{返回元素==b;});如果(!isIn){a.推动(b);}返回a;}, []);}let ret=唯一(数字);//[1, 2, 3, 4]控制台日志(ret);

通用功能方法

以下是ES2015的通用和严格功能方法:

//小型、可重复使用的辅助功能常量应用=f=>a=>f(a);常量flip=f=>b=>a=>f(a)(b);常量未修正=f=>(a,b)=>f(a)(b);常量push=x=>xs=>(xs.push(x),xs);常量foldl=f=>acc=>xs=>xs.reduce(uncurry(f),acc);常量some=f=>xs=>xs.some(apply(f));//实际的重复数据消除功能常量uniqueBy=f=>foldl(acc=>x=>一些(f(x))(acc)? 应收账款:推(x)(acc)) ([]);//比较器常量eq=y=>x=>x===y;//字符串相等不区分大小写:D常量seqCI=y=>x=>x.toLowerCase()===y.toLowerCase();//模拟数据常量xs=[1,2,3,1,2,3,4];常量ys=[“a”、“b”、“c”、“a”、“b”、“c”、“D”];console.log(uniqueBy(eq)(xs));console.log(uniqueBy(seqCI)(ys));

我们可以很容易地从unqiueBy中派生出唯一的,或者使用Sets更快地实现:

const unqiue = uniqueBy(eq);

// const unique = xs => Array.from(new Set(xs));

此方法的优点:

使用单独比较器函数的通用解决方案声明性和简洁的实现其他小型通用函数的重用

性能注意事项

uniqueBy不如具有循环的命令式实现快,但由于它的泛型性,它更具表现力。

如果您确定uniqueBy是应用程序中具体性能损失的原因,请用优化的代码替换它。也就是说,首先以功能性、声明性的方式编写代码。之后,如果您遇到性能问题,请尝试在导致问题的位置优化代码。

内存消耗和垃圾收集

uniqueBy利用隐藏在其体内的突变(push(x)(acc))。它重用累加器,而不是在每次迭代后丢弃它。这减少了内存消耗和GC压力。由于这种副作用被包装在函数内部,所以外部的一切都保持纯净。

此解决方案使用了一个新数组和函数内部的对象映射。它所做的就是循环遍历原始数组,并将每个整数添加到对象映射中

`if (!unique[int])`

捕获此错误,因为对象上已存在具有相同编号的键属性。因此,跳过该数字,不允许将其推入新数组。

    function removeRepeats(ints) {
      var unique = {}
      var newInts = []

      for (var i = 0; i < ints.length; i++) {
        var int = ints[i]

        if (!unique[int]) {
          unique[int] = 1
          newInts.push(int)
        }
      }
      return newInts
    }

    var example = [100, 100, 100, 100, 500]
    console.log(removeRepeats(example)) // prints [100, 500]