我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
const a = ['a', 'b', 'b']
function findDuplicates(a) {
return Object.keys(_.pickBy(_.countBy(a), x => x > 1))
}
https://runkit.com/nitzanav/62659f09bd2d5f0008ef46d4
其他回答
如果你想消除重复,试试这个好方法:
函数eliminateduplicate (arr) { var我, Len = arrr .length, Out = [], Obj = {}; For (i = 0;I < len;我+ +){ Obj [arr[i]] = 0; } 对于(i in obj) { out.push(我); } 返回; } console.log (eliminateDuplicates([1、6、7、3、6、8、1,3,4,5,1、7、2、6]))
来源: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
这是一个有趣而简单的任务,有许多难以阅读的答案……
打印稿
function getDuplicatedItems<T>(someArray: T[]): T[] {
// create a set to iterate through (we only need to check each value once)
const itemSet = new Set<T>(someArray);
// from that Set, we check if any of the items are duplicated in someArray
const duplicatedItems = [...itemSet].filter(
(item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
);
return duplicatedItems;
}
JavaScript
function getDuplicatedItems(someArray) {
// check for misuse if desired
// if (!Array.isArray(someArray)) {
// throw new TypeError(`getDuplicatedItems requires an Array type, received ${typeof someArray} type.`);
// }
const itemSet = new Set(someArray);
const duplicatedItems = [...itemSet].filter(
(item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
);
return duplicatedItems;
}
使用Pure Js
function arr(){
var a= [1,2,3,4,5,34,2,5,7,8,6,4,3,25,8,34,56,7,8,76,4,23,34,46,575,8564,53,5345657566];
var b= [];
b.push(a[0]);
var z=0;
for(var i=0; i< a.length; i++){
for(var j=0; j< b.length; j++){
if(b[j] == a[i]){
z = 0;
break;
}
else
z = 1;
}
if(z)
b.push(a[i]);
}
console.log(b);
}
下面是使用sort()和JSON.stringify()实现的一个
https://gist.github.com/korczis/7598657
function removeDuplicates(vals) {
var res = [];
var tmp = vals.sort();
for (var i = 0; i < tmp.length; i++) {
res.push(tmp[i]);
while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
i++;
}
}
return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));
还有一种方法是使用下划线。Numbers是源数组,dupes可能有重复的值。
var itemcounts = _.countBy(numbers, function (n) { return n; });
var dupes = _.reduce(itemcounts, function (memo, item, idx) {
if (item > 1)
memo.push(idx);
return memo;
}, []);