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

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

类似的问题:

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


当前回答

/* 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;
}

其他回答

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

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

带有注释的代码。

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']

这个答案可能也有帮助,它利用js的reduce操作符/方法从数组中删除重复项。

Const result =[1,2,2,3,3,3,3]。Reduce ((x, y) => x.includes(y) ?X:[…]X, y], []); console.log(结果);

基于@ blumoon但更短,返回所有副本一次!

function checkDuplicateKeys(arr) {
    const counts = {}
    return arr.filter((item) => {
        counts[item] = counts[item] || 1
        if (counts[item]++ === 2) return true
    })
}

// [1,2,2,2,2,2,2] => [1,2]
// ['dog', 'dog', 'cat'] => ['dog']

遵循逻辑会更容易、更快

// @Param:data:Array that is the source 
// @Return : Array that have the duplicate entries
findDuplicates(data: Array<any>): Array<any> {
        return Array.from(new Set(data)).filter((value) => data.indexOf(value) !== data.lastIndexOf(value));
      }

优点:

单行:-P 所有内置的数据结构有助于提高效率 快

逻辑描述:

转换为集以删除所有重复项 遍历设置的值 对于每个设置值,在源数组中检查条件"值的第一个索引不等于最后一个索引" == >则推断为重复否则为'唯一'

注意:map()和filter()方法更高效、更快。

魔法

a.filter(( t={}, e=>!(1-(t[e]=++t[e]|0)) )) 

O (n)的性能;我们假设你的数组在a中,它包含可以以唯一方式转换. tostring()的元素(这是由JS在t[e]中隐式完成的),例如numbers=[4,5,4], strings=["aa","bb","aa"], arraysNum=[[1,2,3],[43,2,3],[1,2,3]]。这里有解释,这里有唯一值

var a1 = [[2, 17], [2, 17], [2, 17], [1, 12], [5, 9], [1, 12], [6,2], [1, 12]]; var a2 =[“迈克”,“亚当”,“马特”、“南希”,“亚当”,“珍妮”,“南希”,“卡尔”); Var a3 = [5,6,4,9,2,3,5,3,4,1,5,4,9]; 让nd = (a) = > a.filter ((t = {}, e = > ! (1 - (t [e] = + + t [e] | 0)))) / /打印 let c= x => console.log(JSON.stringify(x)); C (nd(a1)); C (nd(a2)); C (nd(a3));