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

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

类似的问题:

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


当前回答

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

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

其他回答

var a = ["a","a","b","c","c"];

a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})

删除重复项的最短方法是使用Set和Spread语法

const remove = (array) => [...new Set(array)];
console.log(remove([1,1,2,2,3]); //1,2,3

您可以对数组进行排序,然后遍历它,然后查看下一个(或上一个)索引是否与当前索引相同。假设你的排序算法是好的,这个应该小于O(n2):

const findDuplicates = (arr) => { let sorted_arr = arr.slice().sort(); // You can define the comparing function here. // JS by default uses a crappy string compare. // (we use slice to clone the array so the // original array won't be modified) let results = []; for (let i = 0; i < sorted_arr.length - 1; i++) { if (sorted_arr[i + 1] == sorted_arr[i]) { results.push(sorted_arr[i]); } } return results; } let duplicatedArray = [9, 9, 111, 2, 3, 4, 4, 5, 7]; console.log(`The duplicates in ${duplicatedArray} are ${findDuplicates(duplicatedArray)}`);

在这种情况下,如果你要返回一个重复的函数。这是为类似类型的情况。

参考:https://stackoverflow.com/a/57532964/8119511

const a = ['a', 'b', 'b']

function findDuplicates(a) {
    return Object.keys(_.pickBy(_.countBy(a), x => x > 1))
}

https://runkit.com/nitzanav/62659f09bd2d5f0008ef46d4

你可以使用下面的代码来获取给定数组中的重复元素:

let name = ['satya', 'amit', 'aditya', 'abhay', 'satya', 'amit'];
let dup = [];
let uniq = [];
name.forEach((item, index) => {
  if(!uniq.includes(item)) {
    uniq[index] = item;
  }
  if (name.indexOf(item, index + 1) != -1) {
    dup[index] = item;
  }
})