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

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

类似的问题:

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


当前回答

我只需要找到复制的值是什么——实际上我不需要它们的索引,也不需要它们复制了多少次。

这是一个有趣而简单的任务,有许多难以阅读的答案……

打印稿

function getDuplicatedItems<T>(someArray: T[]): T[] {
    // create a set to iterate through (we only need to check each value once)
    const itemSet = new Set<T>(someArray);

    // from that Set, we check if any of the items are duplicated in someArray
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );

    return duplicatedItems;
}

JavaScript

function getDuplicatedItems(someArray) {
    // check for misuse if desired
    // if (!Array.isArray(someArray)) {
    //     throw new TypeError(`getDuplicatedItems requires an Array type, received ${typeof someArray} type.`);
    // }
    const itemSet = new Set(someArray);
    const duplicatedItems = [...itemSet].filter(
        (item) => someArray.indexOf(item) !== someArray.lastIndexOf(item)
    );
    return duplicatedItems;
}

其他回答

在一次采访中有人问我这个问题,我的回答是,

List<int> getDublicates(List<int> x)
{
   List<int> result = new List<int>();
   while (x.Count>0)
   {
      int d = x[0];
      x.Remove(x[0]);
      if (x.Contains(d)) 
      result.Add(d);
   }
   return result;
}

它的性能很好

var array = ['a', 'b', 'c', 'a'];

function unique(array) {
    var unique_arr = [];
    array.forEach(function(i, e) {
        if (unique_arr.indexOf(i)===-1) unique_arr.push(i);
    });
    return unique_arr;
}
console.log(unique(array));

遵循逻辑会更容易、更快

// @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()方法更高效、更快。

我刚刚想出了一个简单的方法来实现这一点,使用数组过滤器

Var list = [9,9,111, 2,3,4,4,5,7]; //筛选1:找到所有重复的元素 Var duplicate = list.filter(函数(值,索引,self) { == self.lastIndexOf(value) && self.indexOf(value) === index; }); console.log(副本);

快速和优雅的方式使用es6对象解构和减少

它在O(n)(对数组进行1次迭代)中运行,并且不会重复出现超过2次的值

const arr =['你好','嗨',“你好”,“再见”,“再见”,“自闭症”) const { dup } = arr.reduce( (acc, curr) => { acc。Items [curr] = acc。项目(咕咕叫)?acc。项目[curr] += 1: 1 如果(acc)。项目[curr] === 2) acc.dup.push(curr) 返回acc }, { 项目:{}, dup: [] }, ) console.log (dup) // ['hi', 'bye']