我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
var input = ['a', 'b', 'a', 'c', 'c'],
duplicates = [],
i, j;
for (i = 0, j = input.length; i < j; i++) {
if (duplicates.indexOf(input[i]) === -1 && input.indexOf(input[i], i+1) !== -1) {
duplicates.push(input[i]);
}
}
console.log(duplicates);
其他回答
更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列O(1)查找时间(在原语数组上惟一地运行是O(n))。对象查找通过在遍历对象时用唯一id标记对象来优化,因此识别重复对象也是每个项目O(1),整个列表O(n)。唯一的例外是被冻结的项目,但这种情况很少见,并且使用数组和indexOf提供了一个回退。
var unique = function(){
var hasOwn = {}.hasOwnProperty,
toString = {}.toString,
uids = {};
function uid(){
var key = Math.random().toString(36).slice(2);
return key in uids ? uid() : uids[key] = key;
}
function unique(array){
var strings = {}, numbers = {}, others = {},
tagged = [], failed = [],
count = 0, i = array.length,
item, type;
var id = uid();
while (i--) {
item = array[i];
type = typeof item;
if (item == null || type !== 'object' && type !== 'function') {
// primitive
switch (type) {
case 'string': strings[item] = true; break;
case 'number': numbers[item] = true; break;
default: others[item] = item; break;
}
} else {
// object
if (!hasOwn.call(item, id)) {
try {
item[id] = true;
tagged[count++] = item;
} catch (e){
if (failed.indexOf(item) === -1)
failed[failed.length] = item;
}
}
}
}
// remove the tags
while (count--)
delete tagged[count][id];
tagged = tagged.concat(failed);
count = tagged.length;
// append primitives to results
for (i in strings)
if (hasOwn.call(strings, i))
tagged[count++] = i;
for (i in numbers)
if (hasOwn.call(numbers, i))
tagged[count++] = +i;
for (i in others)
if (hasOwn.call(others, i))
tagged[count++] = others[i];
return tagged;
}
return unique;
}();
如果你有ES6集合可用,那么有一个更简单、更快的版本。(shim适用于IE9+和其他浏览器:https://github.com/Benvie/ES6-Harmony-Collections-Shim)
function unique(array){
var seen = new Set;
return array.filter(function(item){
if (!seen.has(item)) {
seen.add(item);
return true;
}
});
}
在数组中查找重复的值
这应该是在数组中找到重复值的最短方法之一。正如OP特别要求的那样,这不会删除重复项,而是找到它们。
Var输入= [1,2,3,1,3,1]; Var duplicate =输入。Reduce(函数(acc, el, i, arr) { if (arr.indexOf(el) !== i && ac . indexof (el) < 0) ac .push(el);返回acc; },[]); document . write(副本);// = 1,3(实际数组= [1,3])
这不需要排序或任何第三方框架。它也不需要手动循环。它适用于indexOf()(或者更清楚地说:严格比较运算符)支持的所有值。
因为reduce()和indexOf(),它至少需要ie9。
这是基于出现次数的更高级的函数。
function getMostDuplicated(arr, count) {
const result = [];
arr.forEach((item) => {
let i = 0;
arr.forEach((checkTo) => {
if (item === checkTo) {
i++;
if (i === count && result.indexOf(item) === -1) {
result.push(item);
}
}
});
});
return result;
}
arr = [1,1,1,2,5,67,3,2,3,2,3,1,2,3,4,1,4];
result = getMostDuplicated(arr, 5); // result is 1
result = getMostDuplicated(arr, 2); // result 1, 2, 3, 4
console.log(result);
我更喜欢函数法。
function removeDuplicates(links) {
return _.reduce(links, function(list, elem) {
if (list.indexOf(elem) == -1) {
list.push(elem);
}
return list;
}, []);
}
它使用下划线,但Array也有一个reduce函数
我试过了,你会得到唯一的元素和在两个不同数组中重复的元素。
复杂度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);