我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
排名较高的答案有一些固有的问题,包括使用遗留的javascript,不正确的排序或只支持2个重复的项目。
这里有一个解决这些问题的现代解决方案:
const arrayNonUniq = array => {
if (!Array.isArray(array)) {
throw new TypeError("An array must be provided!")
}
return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}
arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]
arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']
你也可以使用npm包array-non-uniq。
其他回答
var a = ["a","a","b","c","c"];
a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
这是一个方法,以避免重复到javascript数组…它支持字符串和数字…
var unique = function(origArr) {
var newArray = [],
origLen = origArr.length,
found,
x = 0; y = 0;
for ( x = 0; x < origLen; x++ ) {
found = undefined;
for ( y = 0; y < newArray.length; y++ ) {
if ( origArr[x] === newArray[y] ) found = true;
}
if ( !found) newArray.push( origArr[x] );
}
return newArray;
}
检查这个小提琴..
Var arr = [2,1,2,2,4,4,2,5]; 函数returnduplicate (arr) { 加勒比海盗。Reduce(函数(dupes, val, i) { 如果(arr.indexOf (val) ! = =我& & dupes.indexOf (val) = = = 1) { dupes.push (val); } 返回欺骗; },[]); } alert (returnDuplicates (arr));
这个函数避免了排序步骤,并使用reduce()方法将重复项推入一个新数组(如果该数组中不存在)。
这是我能想到的最简单的解决办法:
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)
希望这能有所帮助。
这是我能想到的最有效的方法,因为不包括Array.indexOf()或Array.lastIndexOf(),它们的复杂度为O(n),并且在复杂度为O(n)的任何循环中使用将使完整的复杂度为O(n²)。
我的第一个循环的复杂度是O(n/2)或O((n/2) + 1),因为在哈希中搜索的复杂度是O(1)。当数组中没有重复元素时,第二个循环的最差复杂度为O(n),当每个元素都有重复元素时,最佳复杂度为O(n/2)。
function duplicates(arr) {
let duplicates = [],
d = {},
i = 0,
j = arr.length - 1;
// Complexity O(n/2)
while (i <= j) {
if (i === j)
d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1; // Complexity O(1)
else {
d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1; // Complexity O(1)
d[arr[j]] ? d[arr[j]] += 1 : d[arr[j]] = 1; // Complexity O(1)
}
++i;
--j;
}
// Worst complexity O(n), best complexity O(n/2)
for (let k in d) {
if (d[k] > 1)
duplicates.push(k);
}
return duplicates;
}
console.log(duplicates([5,6,4,9,2,3,5,3,4,1,5,4,9]));
console.log(duplicates([2,3,4,5,4,3,4]));
console.log(duplicates([4,5,2,9]));
console.log(duplicates([4,5,2,9,2,5,9,4]));