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

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

类似的问题:

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


当前回答

已经有很多答案了,但不幸的是,有些太长了,有些太短了,但对我来说太神秘了,而另一些则超出了我的知识范围……不过,我真的很喜欢我提出的这个解决方案。希望它仍然对一些人有帮助!

尽管最初的帖子说他/她实际上不需要重复的索引,也不需要重复多少次,但我认为仍然需要清楚地计算它们。

带有注释的代码。

function findDuplicates(array, count = {}) {
  // with count declared in the parameter, initialized as an empty object, 
  // it can store the counts of all elements in array  
  
  // using the forEach loop to iterate through the input array, 
  // also using the conditional ternary operators 
  // (works just like a normal if-else statement, but just a bit cleaner)
  // we can store all occurrences of each element from array in count
  array.forEach(el => count[el] ? count[el]++ : count[el] = 1)
  
  // using Object.keys, we get an array of all keys from count (all numbers) 
  // (sorted as well, though of no specific importance here)
  // using filter to find all elements with a count (value) > 1 (duplicates!)
  return Object.keys(count).filter(key => count[key] > 1);
}

只有代码(带有测试用例)。

函数findduplicate(数组,count = {}) { 数组中。forEach(el => count[el] ?Count [el]++: Count [el] = 1); 返回种(计数)。Filter (key => count[key] > 1); } 让arr1 = [9,9,111, 2,3,4,4,5,7]; 让arr2 = [1,6,7,3,6,8,1,3,4,5,1,7,2,6]; console.log (findDuplicates (arr1));// => ['4', '9'] console.log (findDuplicates (arr2));// => ['1', '3', '6', '7']

其他回答

这是我能想到的最简单的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] */

修改@RaphaelMontanaro的解决方案,借鉴@Nosredna的博客,如果你只想从数组中识别重复的元素,下面是你可以做的事情。

function identifyDuplicatesFromArray(arr) {
        var i;
        var len = arr.length;
        var obj = {};
        var duplicates = [];

        for (i = 0; i < len; i++) {

            if (!obj[arr[i]]) {

                obj[arr[i]] = {};

            }

            else
            {
                duplicates.push(arr[i]);
            }

        }
        return duplicates;
    }

感谢你优雅的解决方案,@Nosredna!

我试图改善@swilliams的答案,这将返回一个没有重复的数组。

// arrays for testing
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];

// ascending order
var sorted_arr = arr.sort(function(a,b){return a-b;}); 

var arr_length = arr.length;
var results = [];
if(arr_length){
    if(arr_length == 1){
        results = arr;
    }else{
        for (var i = 0; i < arr.length - 1; i++) {
            if (sorted_arr[i + 1] != sorted_arr[i]) {
                results.push(sorted_arr[i]);
            }
            // for last element
            if (i == arr.length - 2){
                results.push(sorted_arr[i+1]);
            }
        }
    }
}

alert(results);
var a = ["a","a","b","c","c"];

a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})

我认为下面是完成你要求的最简单和最快的O(n)方法:

function getDuplicates( arr ) {
  var i, value;
  var all = {};
  var duplicates = [];

  for( i=0; i<arr.length; i++ ) {
    value = arr[i];
    if( all[value] ) {
      duplicates.push( value );
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
  }

  return duplicates;
}

对于ES5或更高版本:

function getDuplicates( arr ) {
  var all = {};
  return arr.reduce(function( duplicates, value ) {
    if( all[value] ) {
      duplicates.push(value);
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
    return duplicates;
  }, []);
}