我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
删除重复项的最短方法是使用Set和Spread语法
const remove = (array) => [...new Set(array)];
console.log(remove([1,1,2,2,3]); //1,2,3
其他回答
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.
这应该能得到你想要的,只是副本。
function find_duplicates(arr) {
var len=arr.length,
out=[],
counts={};
for (var i=0;i<len;i++) {
var item = arr[i];
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
if (counts[item] === 2) {
out.push(item);
}
}
return out;
}
find_duplicates(['one',2,3,4,4,4,5,6,7,7,7,'pig','one']); // -> ['one',4,7] in no particular order.
令人惊讶的是没有人发布这个解决方案。
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>
</title>
</head>
<body>
<script>
var list = [100,33,45,54,9,12,80,100];
var newObj = {};
var newArr = [];
for(var i=0; i<list.length; i++){
newObj[list[i]] = i;
}
for(var j in newObj){
newArr.push(j);
}
console.log(newArr);
</script>
</body>
</html>
我更喜欢函数法。
function removeDuplicates(links) {
return _.reduce(links, function(list, elem) {
if (list.indexOf(elem) == -1) {
list.push(elem);
}
return list;
}, []);
}
它使用下划线,但Array也有一个reduce函数
下面是一个简单的小片段,用于查找唯一的和重复的值,无需排序和两个循环。
Var _unique =函数(arr) { Var h = [], t = []; 加勒比海盗。forEach(函数(n) { if (h.indexOf(n) == -1) h.push (n); 其他t.push (n); }); 返回[h, t]; } var =结果_unique([“测试”,1 4 2,34岁,6日,21日,3,4,“测试”、“王子”、“th”,34]); console.log("Has duplicate values: " + (result[1]. log)长度> 0))//你可以检查重复值的计数 Console.log (result[0]) //唯一值 Console.log (result[1]) //重复值