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

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

类似的问题:

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


当前回答

魔法

a.filter(( t={}, e=>!(1-(t[e]=++t[e]|0)) )) 

O (n)的性能;我们假设你的数组在a中,它包含可以以唯一方式转换. tostring()的元素(这是由JS在t[e]中隐式完成的),例如numbers=[4,5,4], strings=["aa","bb","aa"], arraysNum=[[1,2,3],[43,2,3],[1,2,3]]。这里有解释,这里有唯一值

var a1 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6,2], [1, 12]]; var a2 =[“迈克”,“亚当”,“马特”、“南希”,“亚当”,“珍妮”,“南希”,“卡尔”); Var a3 = [5,6,4,9,2,3,5,3,4,1,5,4,9]; 让nd = (a) = > a.filter ((t = {}, e = > ! (1 - (t [e] = + + t [e] | 0)))) / /打印 let c= x => console.log(JSON.stringify(x)); C (nd(a1)); C (nd(a2)); C (nd(a3));

其他回答

非常简单的方法:

函数getDuplicateValues(someArray) { const duplicateValues = new Set([]) const check = new Set([]) someArray。forEach(v => { If (check.has(v)) { duplicateValues.add (v) }其他{ check.add (v) } }) 返回Array.from (duplicateValues); } const result = getDuplicateValues(['咖啡','苏打','水','果汁','水','水','咖啡']) repeated_values。textContent = JSON。Stringify(结果,null, ' ') < pre id = " repeated_values " > < / >之前

大多数答案我都不喜欢。

为什么?太复杂,代码太多,效率低下,许多代码没有回答问题,即找到重复项(而不是给出一个没有重复项的数组)。

Next函数返回所有副本:

function GetDuplicates(arr) {
  var i, out=[], obj={};
  for (i=0; i < arr.length; i++) 
    obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
  return out;
}  

因为在大多数情况下,返回所有重复值是没有用的,而只是告诉存在哪些重复值。在这种情况下,返回一个具有唯一重复项的数组;-)

function GetDuplicates(arr) {
  var i, out=[], obj={};
  for (i=0; i < arr.length; i++)
    obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
  return GetUnique(out);
}

function GetUnique(arr) {
  return $.grep(arr, function(elem, index) {
    return index == $.inArray(elem, arr);
  });
}

也许其他人也这么想。

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.

Var arr = [4,5,1,1,2,3,4,4,7,5,2,6,10,9]; Var sorted_arr = arr.sort(); Var len = arrr .length; Var结果= []; For (var I = 0;I < len;我+ +){ If (sorted_arr[i + 1] !== sorted_arr[i]) { results.push (sorted_arr[我]); } } document . write(结果);

使用underscore.js

function hasDuplicate(arr){
    return (arr.length != _.uniq(arr).length);
}