我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
我试过了,你会得到唯一的元素和在两个不同数组中重复的元素。
复杂度O (n)
let start = [1,1,2,1,3,4,5,6,5,5]; start.sort(); const unique=[]; const repeat = []; let ii=-1 ; for(let i =0 ; i<start.length; i++){ if(start[i]===start[i-1]){ if(repeat[ii]!==start[i-1]){ repeat.push(start[i-1]); ii++; } } else { if(i+1<start.length){ if(start[i]!==start[i+1]){ unique.push(start[i]); } } else if(i===start.length-1){ unique.push(start[i]); } } } console.log(unique) ; console.log(repeat);
其他回答
你可以使用下面的结构:
var arr = [1,2,3,4,5,6,7,8,9,0,5];
var duplicate = arr.filter(function(item, i, arr) {
return -1 !== arr.indexOf(item, i + 1);
})
在这篇文章是有用的重复检查,如果你正在使用Jquery。
如何使用jquery在数组中找到重复项
var unique_values = {}; var list_of_values = []; $('input[name$="recordset"]'). each(function(item) { if ( ! unique_values[item.value] ) { unique_values[item.value] = true; list_of_values.push(item.value); } else { // We have duplicate values! } });
使用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);
}
我试图改善@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);
这是我能想到的最简单的解决办法:
const arr =[1、2、2、2 0,0,0,500,1,“,”“,”“) Const filtered = arr。filter((el, index) => arr.indexOf(el) !== index) // => filtered = [2,2,0,0, -1, 'a', 'a'] Const duplicate =[…]新的(过滤) console.log(副本) // => [2,0, -1, 'a']
就是这样。
注意:
It works with any numbers including 0, strings and negative numbers e.g. -1 - Related question: Get all unique values in a JavaScript array (remove duplicates) The original array arr is preserved (filter returns the new array instead of modifying the original) The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ]) If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)
希望这能有所帮助。