我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。
我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。
类似的问题:
获取JavaScript数组中所有唯一的值(删除重复值)
当前回答
这是我能想到的最简单的解决办法:
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)
希望这能有所帮助。
其他回答
非常简单的方法:
函数getDuplicateValues(someArray) { const duplicateValues = new Set([]) const check = new Set([]) someArray。forEach(v => { If (check.has(v)) { duplicateValues.add (v) }其他{ check.add (v) } }) 返回Array.from (duplicateValues); } const result = getDuplicateValues(['咖啡','苏打','水','果汁','水','水','咖啡']) repeated_values。textContent = JSON。Stringify(结果,null, ' ') < pre id = " repeated_values " > < / >之前
大多数答案我都不喜欢。
为什么?太复杂,代码太多,效率低下,许多代码没有回答问题,即找到重复项(而不是给出一个没有重复项的数组)。
Next函数返回所有副本:
function GetDuplicates(arr) {
var i, out=[], obj={};
for (i=0; i < arr.length; i++)
obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
return out;
}
因为在大多数情况下,返回所有重复值是没有用的,而只是告诉存在哪些重复值。在这种情况下,返回一个具有唯一重复项的数组;-)
function GetDuplicates(arr) {
var i, out=[], obj={};
for (i=0; i < arr.length; i++)
obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
return GetUnique(out);
}
function GetUnique(arr) {
return $.grep(arr, function(elem, index) {
return index == $.inArray(elem, arr);
});
}
也许其他人也这么想。
更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列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;
}
});
}
使用ES6(或使用Babel或Typescipt),你可以简单地做:
var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);
https://es6console.com/j58euhbt/
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);