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

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

类似的问题:

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


当前回答

公认的答案是最完美的,但正如一些用户指出的那样,对于一个元素重复超过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);

其他回答

您可以对数组进行排序,然后遍历它,然后查看下一个(或上一个)索引是否与当前索引相同。假设你的排序算法是好的,这个应该小于O(n2):

const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; } let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7]; console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

在这种情况下,如果你要返回一个重复的函数。这是为类似类型的情况。

参考:https://stackoverflow.com/a/57532964/8119511

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

Prototype库有一个uniq函数,它返回不包含dupes的数组。但这只是工作的一半。

在这篇文章是有用的重复检查,如果你正在使用Jquery。

如何使用jquery在数组中找到重复项

var unique_values = {}; var list_of_values = []; $('input[name$="recordset"]').     each(function(item) {          if ( ! unique_values[item.value] ) {             unique_values[item.value] = true;             list_of_values.push(item.value);         } else {             // We have duplicate values!         }     });

下面是一个没有使用临时数组来存储非重复的数组:

// simple duplicate removal for non-object types
Array.prototype.removeSimpleDupes = function() {
    var i, cntr = 0, arr = this, len = arr.length;

    var uniqueVal = function(val,n,len) { // remove duplicates
        var dupe = false;
            for (i = n; i < len; i++) { 
                if (typeof arr[i]!=="undefined" && val===arr[i]) { arr.splice(i,1); dupe = true; }
            }
        return (dupe) ? arr.length : len;
    };

    while (cntr < len) {
        len = uniqueVal(arr[cntr],cntr+1,len);
        cntr++;
    }

    return arr;
};