我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
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
其他回答
非常简单的方法:
函数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 " > < / >之前
这是我的简单和一行解决方案。
它首先搜索不是唯一的元素,然后使用Set使所找到的数组是唯一的。
最后我们有一个重复的数组。
Var数组= [1,2,2,3,3,4,5,6,2,3,7,8,5,22,1,2,511,12,50,22]; console.log([…新设置( 数组中。filter((value, index, self) => self. indexof (value) !== index))] );
您可以对数组进行排序,然后遍历它,然后查看下一个(或上一个)索引是否与当前索引相同。假设你的排序算法是好的,这个应该小于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
快速和优雅的方式使用es6对象解构和减少
它在O(n)(对数组进行1次迭代)中运行,并且不会重复出现超过2次的值
const arr =['你好','嗨',“你好”,“再见”,“再见”,“自闭症”) const { dup } = arr.reduce( (acc, curr) => { acc。Items [curr] = acc。项目(咕咕叫)?acc。项目[curr] += 1: 1 如果(acc)。项目[curr] === 2) acc.dup.push(curr) 返回acc }, { 项目:{}, dup: [] }, ) console.log (dup) // ['hi', 'bye']
在这里,每个dupe只输出一次副本。
Var arr = [9,9,9,9,111, 2,3,4,4,5,7]; arr.sort (); Var结果= []; For (var I = 0;我< arr。长度- 1;我+ +){ 如果(arr[i + 1] == arr[i]) { results.push (arr[我]); } } results = Array.from(new Set(results)) console.log(结果);