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

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

类似的问题:

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


当前回答

//program to find the duplicate elements in arraylist

import java.util.ArrayList;
import java.util.Scanner;

public class DistinctEle 
{ 
    public static void main(String args[])
    {
        System.out.println("Enter elements");
        ArrayList<Integer> abc=new ArrayList<Integer>();
        ArrayList<Integer> ab=new ArrayList<Integer>();
        Scanner a=new Scanner(System.in);
        int b;
        for(int i=0;i<=10;i++)
        {
            b=a.nextInt();
            if(!abc.contains(b))
            {
                abc.add(b);
            }
            else
            {
                System.out.println("duplicate elements"+b);
            }
        }
    }
}

其他回答

公认的答案是最完美的,但正如一些用户指出的那样,对于一个元素重复超过2次的情况,它将给出具有重复元素的数组:

这个解决方案也涵盖了这些场景:

const peoples = [
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorze"},
  {id: 1, name:"Arjun"},
  {id: 4, name:"dezesseis"},
  {id: 1, name:"Arjun"},
  {id: 2, name:"quinze"},
  {id: 3, name:"catorzee"}
]


function repeated(ppl){

  const newppl = ppl.slice().sort((a,b) => a.id -b.id);

  let rept = [];
  for(let i = 0; i < newppl.length-1 ; i++){
    if (newppl[i+1].id == newppl[i].id){
      rept.push(newppl[i+1]);
    }
  }

  return [...new Set(rept.map(el => el.id))].map(rid => 
    rept.find(el => el.id === rid)
  );

}

repeated(peoples);

魔法

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));

这应该能得到你想要的,只是副本。

function find_duplicates(arr) {
  var len=arr.length,
      out=[],
      counts={};

  for (var i=0;i<len;i++) {
    var item = arr[i];
    counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
    if (counts[item] === 2) {
      out.push(item);
    }
  }

  return out;
}

find_duplicates(['one',2,3,4,4,4,5,6,7,7,7,'pig','one']); // -> ['one',4,7] in no particular order.

这个问题有这么多错误的答案,或者答案像Set一样需要很多额外的内存,这实际上是一个遗憾。干净简单的解决方案:

function findDuplicates<T>(arr: Array<T>): T[] {
  //If the array has less than 2 elements there are no duplicates
  const n = arr.length;
  if (n < 2)
    return [];
  
  const sorted = arr.sort();
  const result = [];

  //Head
  if (sorted[0] === sorted[1])
    result.push(sorted[0]);

  //Inner (Head :: Inner :: Tail)
  for (let i = 1; i < n-1; i++) {
    const elem = sorted[i];
    if (elem === sorted[i - 1] || elem === sorted[i+1])
      result.push(elem)
  }

  //Tail
  if (sorted[n - 1] == sorted[n - 2])
    result.push(sorted[n - 1]);

  return result;
}

console.dir(findDuplicates(['a', 'a', 'b', 'b']));
console.dir(findDuplicates(['a', 'b']));
console.dir(findDuplicates(['a', 'a', 'a']));
console.dir(findDuplicates(['a']));
console.dir(findDuplicates([]));

这里有一个非常简单的方法:

var codes = dc_1.split(',');
var i = codes.length;
while (i--) {
  if (codes.indexOf(codes[i]) != i) {
    codes.splice(i,1);
  }
}