我需要检查一个JavaScript数组,看看是否有任何重复的值。最简单的方法是什么?我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

我知道我可以循环遍历数组并检查所有其他值是否匹配,但似乎应该有更简单的方法。

类似的问题:

获取JavaScript数组中所有唯一的值(删除重复值)


当前回答

下面是一个没有使用临时数组来存储非重复的数组:

// simple duplicate removal for non-object types
Array.prototype.removeSimpleDupes = function() {
    var i, cntr = 0, arr = this, len = arr.length;

    var uniqueVal = function(val,n,len) { // remove duplicates
        var dupe = false;
            for (i = n; i < len; i++) { 
                if (typeof arr[i]!=="undefined" && val===arr[i]) { arr.splice(i,1); dupe = true; }
            }
        return (dupe) ? arr.length : len;
    };

    while (cntr < len) {
        len = uniqueVal(arr[cntr],cntr+1,len);
        cntr++;
    }

    return arr;
};

其他回答

从数组/字符串中获取重复/重复值的最简单方法:

函数getduplicate (param) { Var duplicate = {} For (var I = 0;I < param.length;我+ +){ Var char = param[i] 如果(重复[char]) { 副本(char) + + }其他{ duplicate [char] = 1 } } 返回副本 } console.log (getDuplicates(“aeiouaeiou”)); console.log (getDuplicates((“a”、“e”、“我”、“o”、“u”,“一个”,“e”))); console.log(getduplicate ([1,2,3,4,5,1,1,2,3]));

/* Array对象的indexOf方法用于比较数组项。 IE是唯一一个原生不支持它的主流浏览器,但它很容易实现: * /

Array.prototype.indexOf= Array.prototype.indexOf || function(what, i){
    i= i || 0;
    var L= this.length;
    while(i<L){
        if(this[i]=== what) return i;
        ++i;
    }
    return -1;
}

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1 && dups.indexOf(itm)== -1){
            dups[dups.length]= itm;
        }
    }
    return dups;
}

var a1= [1, 22, 3, 2, 2, 3, 3, 4, 1, 22, 7, 8, 9];

警报(getarrayduplicates (a1));

对于非常大的数组,可以更快地从数组中删除找到的重复项,这样就不会再次查看它们:

function getarrayduplicates(arg){
    var itm, A= arg.slice(0, arg.length), dups= [];
    while(A.length){
        itm= A.shift();
        if(A.indexOf(itm)!= -1){
            dups[dups.length]= itm;
            while(A.indexOf(itm)!= -1){
                A.splice(A.indexOf(itm), 1);
            }
        }
    }
    return dups;
}

我试过了,你会得到唯一的元素和在两个不同数组中重复的元素。

复杂度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);

已经有很多答案了,但不幸的是,有些太长了,有些太短了,但对我来说太神秘了,而另一些则超出了我的知识范围……不过,我真的很喜欢我提出的这个解决方案。希望它仍然对一些人有帮助!

尽管最初的帖子说他/她实际上不需要重复的索引,也不需要重复多少次,但我认为仍然需要清楚地计算它们。

带有注释的代码。

function findDuplicates(array, count = {}) {
  // with count declared in the parameter, initialized as an empty object, 
  // it can store the counts of all elements in array  
  
  // using the forEach loop to iterate through the input array, 
  // also using the conditional ternary operators 
  // (works just like a normal if-else statement, but just a bit cleaner)
  // we can store all occurrences of each element from array in count
  array.forEach(el => count[el] ? count[el]++ : count[el] = 1)
  
  // using Object.keys, we get an array of all keys from count (all numbers) 
  // (sorted as well, though of no specific importance here)
  // using filter to find all elements with a count (value) > 1 (duplicates!)
  return Object.keys(count).filter(key => count[key] > 1);
}

只有代码(带有测试用例)。

函数findduplicate(数组,count = {}) { 数组中。forEach(el => count[el] ?Count [el]++: Count [el] = 1); 返回种(计数)。Filter (key => count[key] > 1); } 让arr1 = [9,9,111, 2,3,4,4,5,7]; 让arr2 = [1,6,7,3,6,8,1,3,4,5,1,7,2,6]; console.log (findDuplicates (arr1));// => ['4', '9'] console.log (findDuplicates (arr2));// => ['1', '3', '6', '7']

这是我在重复线程(!)中的回答:

在2014年写这篇文章时,所有的例子都是for-loops或jQuery。JavaScript有完美的工具:排序、映射和缩减。

找到重复的物品

var名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”) Const uniq = names .map((name) => { 返回{ 数:1 名称:名称 }; }) .reduce((result, b) => { Result [b.name] = (Result [b.name] || 0) + b.count; 返回结果; }, {}); const duplicate = Object.keys(uniq).filter((a) => uniq[a] > 1); console.log(副本);// ['Nancy']

更多函数式语法:

@Dmytro-Laptin指出了一些可以删除的代码。这是相同代码的一个更紧凑的版本。使用一些ES6技巧和高阶函数:

常量名称=[“迈克”,“马特”,“南希”,“亚当”,“珍妮”,“南希”,“卡尔”); Const count = names => 的名字。Reduce ((result, value) =>({… [value]:(result[value] || 0) + 1 }, {});//不要忘记初始化累加器 Const duplicate = dict => Object.keys(dict).filter((a) => dict[a] > 1); console.log (count(名称));//{迈克:1,马特:1,南希:2,亚当:1,珍妮:1,卡尔:1} console.log(副本(count(名字)));// ['Nancy']