我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。

类似的问题:

获取JavaScript数组中所有唯一的值(删除重复值)


当前回答

这是我在重复线程(!)中的回答:

在2014年写这篇文章时,所有的例子都是for-loops或jQuery。JavaScript有完美的工具:排序、映射和缩减。

找到重复的物品

var名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”) Const uniq = names .map((name) => { 返回{ 数:1 名称:名称 }; }) .reduce((result, b) => { Result [b.name] = (Result [b.name] || 0) + b.count; 返回结果; }, {}); const duplicate = Object.keys(uniq).filter((a) => uniq[a] > 1); console.log(副本);// ['Nancy']

更多函数式语法:

@Dmytro-Laptin指出了一些可以删除的代码。这是相同代码的一个更紧凑的版本。使用一些ES6技巧和高阶函数:

常量名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”); Const count = names => 的名字。Reduce ((result, value) =>({… [value]:(result[value] || 0) + 1 }, {});//不要忘记初始化累加器 Const duplicate = dict => Object.keys(dict).filter((a) => dict[a] > 1); console.log (count(名称));//{迈克:1,马特:1,南希:2,亚当:1,珍妮:1,卡尔:1} console.log(副本(count(名字)));// ['Nancy']

其他回答

排名较高的答案有一些固有的问题,包括使用遗留的javascript,不正确的排序或只支持2个重复的项目。

这里有一个解决这些问题的现代解决方案:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

你也可以使用npm包array-non-uniq。

var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});

或者当添加到原型时。阵列链

//copy and paste: without error handling
Array.prototype.unique = 
   function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}

请看这里:https://gist.github.com/1305056

以O(n)时间复杂度(不排序)求解上述问题。

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];

var obj={};

for(var i=0;i<arr.length;i++){
    if(!obj[arr[i]]){
        obj[arr[i]]=1;
    } else {
        obj[arr[i]]=obj[arr[i]]+1;
    }
}
var result=[]
for(var key in obj){
    if(obj[key]>1){
        result.push(Number(key)) // change this to result.push(key) to find duplicate strings in an array
    }
}

console.log(result)

更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列O(1)查找时间(在原语数组上惟一地运行是O(n))。对象查找通过在遍历对象时用唯一id标记对象来优化,因此识别重复对象也是每个项目O(1),整个列表O(n)。唯一的例外是被冻结的项目,但这种情况很少见,并且使用数组和indexOf提供了一个回退。

var unique = function(){
  var hasOwn = {}.hasOwnProperty,
      toString = {}.toString,
      uids = {};

  function uid(){
    var key = Math.random().toString(36).slice(2);
    return key in uids ? uid() : uids[key] = key;
  }

  function unique(array){
    var strings = {}, numbers = {}, others = {},
        tagged = [], failed = [],
        count = 0, i = array.length,
        item, type;

    var id = uid();

    while (i--) {
      item = array[i];
      type = typeof item;
      if (item == null || type !== 'object' && type !== 'function') {
        // primitive
        switch (type) {
          case 'string': strings[item] = true; break;
          case 'number': numbers[item] = true; break;
          default: others[item] = item; break;
        }
      } else {
        // object
        if (!hasOwn.call(item, id)) {
          try {
            item[id] = true;
            tagged[count++] = item;
          } catch (e){
            if (failed.indexOf(item) === -1)
              failed[failed.length] = item;
          }
        }
      }
    }

    // remove the tags
    while (count--)
      delete tagged[count][id];

    tagged = tagged.concat(failed);
    count = tagged.length;

    // append primitives to results
    for (i in strings)
      if (hasOwn.call(strings, i))
        tagged[count++] = i;

    for (i in numbers)
      if (hasOwn.call(numbers, i))
        tagged[count++] = +i;

    for (i in others)
      if (hasOwn.call(others, i))
        tagged[count++] = others[i];

    return tagged;
  }

  return unique;
}();

如果你有ES6集合可用,那么有一个更简单、更快的版本。(shim适用于IE9+和其他浏览器:https://github.com/Benvie/ES6-Harmony-Collections-Shim)

function unique(array){
  var seen = new Set;
  return array.filter(function(item){
    if (!seen.has(item)) {
      seen.add(item);
      return true;
    }
  });
}

我们将使用Javascript ES6功能来做魔术!

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
const filtered = arr.filter((value, index) => {
 return arr.indexOf(value) >= index;
});

console.log(filtered);

https://jsfiddle.net/97Lxupnz/