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

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

类似的问题:

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


当前回答

function GetDuplicates(arr) {
    var i = 0, m = [];
    return arr.filter(function (n) {
        return !m[n] * ~arr.indexOf(n, m[n] = ++i);
    });
}

其他回答

这是基于出现次数的更高级的函数。

function getMostDuplicated(arr, count) {
      const result = [];
      arr.forEach((item) => {
        let i = 0;
        arr.forEach((checkTo) => {
          if (item === checkTo) {
            i++;
            if (i === count && result.indexOf(item) === -1) {
              result.push(item);
            }
          }
        });
      });
      return result;
}

arr = [1,1,1,2,5,67,3,2,3,2,3,1,2,3,4,1,4];
result = getMostDuplicated(arr, 5); // result is 1
result = getMostDuplicated(arr, 2); // result 1, 2, 3, 4
console.log(result);

从Raphael Montanaro的回答,它可以改进使用数组/对象项如下。

function eliminateDuplicates(arr) {
  var len = arr.length,
      out = [],
      obj = {};

  for (var key, i=0; i < len; i++) {
    key = JSON.stringify(arr[i]);
    obj[key] = (obj[key]) ? obj[key] + 1 : 1;
  }
  for (var key in obj) {
    out.push(JSON.parse(key));
  }
  return [out, obj];
}

注意:对于不支持JSON的浏览器,需要使用JSON库。

公认的答案是最完美的,但正如一些用户指出的那样,对于一个元素重复超过2次的情况,它将给出具有重复元素的数组:

这个解决方案也涵盖了这些场景:

const peoples = [
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorze"},
  {id: 1, name:"Arjun"},
  {id: 4, name:"dezesseis"},
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorzee"}
]


function repeated(ppl){

  const newppl = ppl.slice().sort((a,b) => a.id -b.id);

  let rept = [];
  for(let i = 0; i < newppl.length-1 ; i++){
    if (newppl[i+1].id == newppl[i].id){
      rept.push(newppl[i+1]);
    }
  }

  return [...new Set(rept.map(el => el.id))].map(rid => 
    rept.find(el => el.id === rid)
  );

}

repeated(peoples);

您可以使用filter方法和indexOf()来获取所有重复的值

function duplicate(arr) {
    return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index) 
}

arr.indexOf(item)将始终返回给定元素所在的第一个索引 发现

如果你想消除重复,试试这个好方法:

函数eliminateduplicate (arr) { var我, Len = arrr .length, Out = [], Obj = {}; For (i = 0;I < len;我+ +){ Obj [arr[i]] = 0; } 对于(i in obj) { out.push(我); } 返回; } console.log (eliminateDuplicates([1、6、7、3、6、8、1,3,4,5,1、7、2、6]))

来源: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/