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

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

类似的问题:

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


当前回答

使用“includes”测试元素是否已经存在。

Var arr = [1,1,4,5,5], darr = [], duplicate = []; For (var I = 0;I < arrr .length;我+ +){ If (darr.includes(arr[i]) && !重复。includes(arr[i])) duplicates.push (arr[我]) 其他的 darr.push (arr[我]); } console.log(副本); <h3>重复数组</h3> <p>[1,1,4,5,5]</p> <h3>具有不同元素的数组</h3> <p>[1,4,5]</p> <h3>重复值</h3> (1、5)< p > < / p >

其他回答

http://jsfiddle.net/vol7ron/gfJ28/

var arr  = ['hello','goodbye','foo','hello','foo','bar',1,2,3,4,5,6,7,8,9,0,1,2,3];
var hash = [];

// build hash
for (var n=arr.length; n--; ){
   if (typeof hash[arr[n]] === 'undefined') hash[arr[n]] = [];
   hash[arr[n]].push(n);
}


// work with compiled hash (not necessary)
var duplicates = [];
for (var key in hash){
    if (hash.hasOwnProperty(key) && hash[key].length > 1){
        duplicates.push(key);
    }
}    
alert(duplicates);

The result will be the hash array, which will contain both a unique set of values and the position of those values. So if there are 2 or more positions, we can determine that the value has a duplicate. Thus, every place hash[<value>].length > 1, signifies a duplicate. hash['hello'] will return [0,3] because 'hello' was found in node 0 and 3 in arr[]. Note: the length of [0,3] is what's used to determine if it was a duplicate. Using for(var key in hash){ if (hash.hasOwnProperty(key)){ alert(key); } } will alert each unique value.

仅ES5(即,它需要一个filter() polyfill用于IE8及以下):

var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];

arrayToFilter.
    sort().
    filter( function(me,i,arr){
       return (i===0) || ( me !== arr[i-1] );
    });

这个问题有这么多错误的答案,或者答案像Set一样需要很多额外的内存,这实际上是一个遗憾。干净简单的解决方案:

function findDuplicates<T>(arr: Array<T>): T[] {
  //If the array has less than 2 elements there are no duplicates
  const n = arr.length;
  if (n < 2)
    return [];
  
  const sorted = arr.sort();
  const result = [];

  //Head
  if (sorted[0] === sorted[1])
    result.push(sorted[0]);

  //Inner (Head :: Inner :: Tail)
  for (let i = 1; i < n-1; i++) {
    const elem = sorted[i];
    if (elem === sorted[i - 1] || elem === sorted[i+1])
      result.push(elem)
  }

  //Tail
  if (sorted[n - 1] == sorted[n - 2])
    result.push(sorted[n - 1]);

  return result;
}

console.dir(findDuplicates(['a', 'a', 'b', 'b']));
console.dir(findDuplicates(['a', 'b']));
console.dir(findDuplicates(['a', 'a', 'a']));
console.dir(findDuplicates(['a']));
console.dir(findDuplicates([]));

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

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

这是我能想到的最简单的ES5解决方案之一

function duplicates(arr) {
  var duplicatesArr = [],
      uniqueObj = {};

  for (var i = 0; i < arr.length; i++) {
    if( uniqueObj.hasOwnProperty(arr[i]) && duplicatesArr.indexOf( arr[i] ) === -1) {
      duplicatesArr.push( arr[i] );
    }
    else {
      uniqueObj[ arr[i] ] = true;
    }
  }

  return duplicatesArr;
}
/* Input Arr: [1,1,2,2,2,1,3,4,5,3] */
/* OutPut Arr: [1,2,3] */