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

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

类似的问题:

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


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


Prototype库有一个uniq函数,它返回不包含dupes的数组。但这只是工作的一半。


你可以添加这个函数,或者调整它并将其添加到Javascript的数组原型中:

Array.prototype.unique = function () {
    var r = new Array();
    o:for(var i = 0, n = this.length; i < n; i++)
    {
        for(var x = 0, y = r.length; x < y; x++)
        {
            if(r[x]==this[i])
            {
                alert('this is a DUPE!');
                continue o;
            }
        }
        r[r.length] = this[i];
    }
    return r;
}

var arr = [1,2,2,3,3,4,5,6,2,3,7,8,5,9];
var unique = arr.unique();
alert(unique);

如果你想消除重复,试试这个好方法:

函数eliminateduplicate (arr) { var我, Len = arrr .length, Out = [], Obj = {}; For (i = 0;I < len;我+ +){ Obj [arr[i]] = 0; } 对于(i in obj) { out.push(我); } 返回; } console.log (eliminateDuplicates([1、6、7、3、6、8、1,3,4,5,1、7、2、6]))

来源: http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/


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

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.

只是在上面的基础上补充一些理论。

在比较模型中,查找重复项的下界为O(n*log(n))。所以理论上,你不能做得比先排序然后再进行 按顺序列出,删除你找到的任何重复项。

如果你想在线性(O(n))的期望时间内找到重复项,你可以做到 哈希列表的每个元素;如果有冲突,删除/标记为重复, 并继续。


下面的函数(前面提到的eliminateduplates函数的变体)似乎可以做到这一点,它为输入["test", "test2", "test2", 1,1,2,3,4,5,6,7,7,10,22,43,1,5,5,8]返回test2,1,7,7,8]。

请注意,这个问题在JavaScript中比在大多数其他语言中更奇怪,因为JavaScript数组几乎可以容纳任何东西。注意,使用排序的解决方案可能需要提供适当的排序函数——我还没有尝试过这种方法。

这个特殊的实现(至少)适用于字符串和数字。

function findDuplicates(arr) {
    var i,
        len=arr.length,
        out=[],
        obj={};

    for (i=0;i<len;i++) {
        if (obj[arr[i]] != null) {
            if (!obj[arr[i]]) {
                out.push(arr[i]);
                obj[arr[i]] = 1;
            }
        } else {
            obj[arr[i]] = 0;            
        }
    }
    return out;
}

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

从Raphael Montanaro的回答,它可以改进使用数组/对象项如下。

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

  for (var key, i=0; i < len; i++) {
    key = JSON.stringify(arr[i]);
    obj[key] = (obj[key]) ? obj[key] + 1 : 1;
  }
  for (var key in obj) {
    out.push(JSON.parse(key));
  }
  return [out, obj];
}

注意:对于不支持JSON的浏览器,需要使用JSON库。


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

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

我更喜欢函数法。

function removeDuplicates(links) {
    return _.reduce(links, function(list, elem) { 
        if (list.indexOf(elem) == -1) {
            list.push(elem);
        }   
        return list;
    }, []);
}

它使用下划线,但Array也有一个reduce函数


http://jsfiddle.net/vol7ron/gfJ28/

var arr  = ['hello','goodbye','foo','hello','foo','bar',1,2,3,4,5,6,7,8,9,0,1,2,3];
var hash = [];

// build hash
for (var n=arr.length; n--; ){
   if (typeof hash[arr[n]] === 'undefined') hash[arr[n]] = [];
   hash[arr[n]].push(n);
}


// work with compiled hash (not necessary)
var duplicates = [];
for (var key in hash){
    if (hash.hasOwnProperty(key) && hash[key].length > 1){
        duplicates.push(key);
    }
}    
alert(duplicates);

The result will be the hash array, which will contain both a unique set of values and the position of those values. So if there are 2 or more positions, we can determine that the value has a duplicate. Thus, every place hash[<value>].length > 1, signifies a duplicate. hash['hello'] will return [0,3] because 'hello' was found in node 0 and 3 in arr[]. Note: the length of [0,3] is what's used to determine if it was a duplicate. Using for(var key in hash){ if (hash.hasOwnProperty(key)){ alert(key); } } will alert each unique value.


var a = [324,3,32,5,52,2100,1,20,2,3,3,2,2,2,1,1,1].sort();
a.filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});

或者当添加到原型时。阵列链

//copy and paste: without error handling
Array.prototype.unique = 
   function(){return this.sort().filter(function(v,i,o){return i&&v!==o[i-1]?v:0;});}

请看这里:https://gist.github.com/1305056


更新:以下使用一个优化的组合策略。它优化了原语查找,以受益于散列O(1)查找时间(在原语数组上惟一地运行是O(n))。对象查找通过在遍历对象时用唯一id标记对象来优化,因此识别重复对象也是每个项目O(1),整个列表O(n)。唯一的例外是被冻结的项目,但这种情况很少见,并且使用数组和indexOf提供了一个回退。

var unique = function(){
  var hasOwn = {}.hasOwnProperty,
      toString = {}.toString,
      uids = {};

  function uid(){
    var key = Math.random().toString(36).slice(2);
    return key in uids ? uid() : uids[key] = key;
  }

  function unique(array){
    var strings = {}, numbers = {}, others = {},
        tagged = [], failed = [],
        count = 0, i = array.length,
        item, type;

    var id = uid();

    while (i--) {
      item = array[i];
      type = typeof item;
      if (item == null || type !== 'object' && type !== 'function') {
        // primitive
        switch (type) {
          case 'string': strings[item] = true; break;
          case 'number': numbers[item] = true; break;
          default: others[item] = item; break;
        }
      } else {
        // object
        if (!hasOwn.call(item, id)) {
          try {
            item[id] = true;
            tagged[count++] = item;
          } catch (e){
            if (failed.indexOf(item) === -1)
              failed[failed.length] = item;
          }
        }
      }
    }

    // remove the tags
    while (count--)
      delete tagged[count][id];

    tagged = tagged.concat(failed);
    count = tagged.length;

    // append primitives to results
    for (i in strings)
      if (hasOwn.call(strings, i))
        tagged[count++] = i;

    for (i in numbers)
      if (hasOwn.call(numbers, i))
        tagged[count++] = +i;

    for (i in others)
      if (hasOwn.call(others, i))
        tagged[count++] = others[i];

    return tagged;
  }

  return unique;
}();

如果你有ES6集合可用,那么有一个更简单、更快的版本。(shim适用于IE9+和其他浏览器:https://github.com/Benvie/ES6-Harmony-Collections-Shim)

function unique(array){
  var seen = new Set;
  return array.filter(function(item){
    if (!seen.has(item)) {
      seen.add(item);
      return true;
    }
  });
}

function remove_dups(arrayName){
  var newArray = new Array();

  label:for(var i=0; i<arrayName.length; i++ ){  

     for(var j=0; j<newArray.length;j++ ){
       if(newArray[j]==arrayName[i]){
         continue label;
       }
     }

     newArray[newArray.length] = arrayName[i];

  }

  return newArray;
}

在这篇文章是有用的重复检查,如果你正在使用Jquery。

如何使用jquery在数组中找到重复项

var unique_values = {}; var list_of_values = []; $('input[name$="recordset"]').     each(function(item) {          if ( ! unique_values[item.value] ) {             unique_values[item.value] = true;             list_of_values.push(item.value);         } else {             // We have duplicate values!         }     });

仅ES5(即,它需要一个filter() polyfill用于IE8及以下):

var arrayToFilter = [ 4, 5, 5, 5, 2, 1, 3, 1, 1, 2, 1, 3 ];

arrayToFilter.
    sort().
    filter( function(me,i,arr){
       return (i===0) || ( me !== arr[i-1] );
    });

使用underscore.js

function hasDuplicate(arr){
    return (arr.length != _.uniq(arr).length);
}

var input = ['a', 'b', 'a', 'c', 'c'],
    duplicates = [],
    i, j;
for (i = 0, j = input.length; i < j; i++) {
  if (duplicates.indexOf(input[i]) === -1 && input.indexOf(input[i], i+1) !== -1) {
    duplicates.push(input[i]);
  }
}

console.log(duplicates);

这是一个方法,以避免重复到javascript数组…它支持字符串和数字…

 var unique = function(origArr) {
    var newArray = [],
        origLen = origArr.length,
        found,
        x = 0; y = 0;

    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArray.length; y++ ) {
            if ( origArr[x] === newArray[y] ) found = true;
        }
        if ( !found) newArray.push( origArr[x] );    
    }
   return newArray;
}

检查这个小提琴..


我试图改善@swilliams的答案,这将返回一个没有重复的数组。

// arrays for testing
var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];

// ascending order
var sorted_arr = arr.sort(function(a,b){return a-b;}); 

var arr_length = arr.length;
var results = [];
if(arr_length){
    if(arr_length == 1){
        results = arr;
    }else{
        for (var i = 0; i < arr.length - 1; i++) {
            if (sorted_arr[i + 1] != sorted_arr[i]) {
                results.push(sorted_arr[i]);
            }
            // for last element
            if (i == arr.length - 2){
                results.push(sorted_arr[i+1]);
            }
        }
    }
}

alert(results);

还有一种方法是使用下划线。Numbers是源数组,dupes可能有重复的值。

var itemcounts = _.countBy(numbers, function (n) { return n; });
var dupes = _.reduce(itemcounts, function (memo, item, idx) {
    if (item > 1)
        memo.push(idx);
    return memo;
}, []);

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

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

我认为下面是完成你要求的最简单和最快的O(n)方法:

function getDuplicates( arr ) {
  var i, value;
  var all = {};
  var duplicates = [];

  for( i=0; i<arr.length; i++ ) {
    value = arr[i];
    if( all[value] ) {
      duplicates.push( value );
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
  }

  return duplicates;
}

对于ES5或更高版本:

function getDuplicates( arr ) {
  var all = {};
  return arr.reduce(function( duplicates, value ) {
    if( all[value] ) {
      duplicates.push(value);
      all[value] = false;
    } else if( typeof all[value] == "undefined" ) {
      all[value] = true;
    }
    return duplicates;
  }, []);
}

下面是使用sort()和JSON.stringify()实现的一个

https://gist.github.com/korczis/7598657

function removeDuplicates(vals) {
    var res = [];
    var tmp = vals.sort();

    for (var i = 0; i < tmp.length; i++) {
        res.push(tmp[i]);
                    while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
            i++;
        }
    }

    return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));

令人惊讶的是没有人发布这个解决方案。

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>
</title>
</head>
<body>
  <script>
       var list = [100,33,45,54,9,12,80,100];
       var newObj = {};
       var newArr = [];
        for(var i=0; i<list.length; i++){
          newObj[list[i]] = i;               
        }
        for(var j in newObj){
            newArr.push(j);  
        }
       console.log(newArr);
  </script>
</body>
</html>

修改@RaphaelMontanaro的解决方案,借鉴@Nosredna的博客,如果你只想从数组中识别重复的元素,下面是你可以做的事情。

function identifyDuplicatesFromArray(arr) {
        var i;
        var len = arr.length;
        var obj = {};
        var duplicates = [];

        for (i = 0; i < len; i++) {

            if (!obj[arr[i]]) {

                obj[arr[i]] = {};

            }

            else
            {
                duplicates.push(arr[i]);
            }

        }
        return duplicates;
    }

感谢你优雅的解决方案,@Nosredna!


大多数答案我都不喜欢。

为什么?太复杂,代码太多,效率低下,许多代码没有回答问题,即找到重复项(而不是给出一个没有重复项的数组)。

Next函数返回所有副本:

function GetDuplicates(arr) {
  var i, out=[], obj={};
  for (i=0; i < arr.length; i++) 
    obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
  return out;
}  

因为在大多数情况下,返回所有重复值是没有用的,而只是告诉存在哪些重复值。在这种情况下,返回一个具有唯一重复项的数组;-)

function GetDuplicates(arr) {
  var i, out=[], obj={};
  for (i=0; i < arr.length; i++)
    obj[arr[i]] == undefined ? obj[arr[i]] ++ : out.push(arr[i]);
  return GetUnique(out);
}

function GetUnique(arr) {
  return $.grep(arr, function(elem, index) {
    return index == $.inArray(elem, arr);
  });
}

也许其他人也这么想。


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

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


这可能是从数组中永久删除重复项的最快方法之一 比大多数函数快10倍。safari快78倍

function toUnique(a,b,c){//array,placeholder,placeholder
 b=a.length;
 while(c=--b)while(c--)a[b]!==a[c]||a.splice(c,1)
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
toUnique(array);
console.log(array);

测试:http://jsperf.com/wgu 演示:http://jsfiddle.net/46S7g/ 更多:https://stackoverflow.com/a/25082874/2450730

如果你不能阅读上面的代码,请阅读javascript书籍,或者这里有一些关于较短代码的解释。https://stackoverflow.com/a/21353032/2450730

编辑 正如注释中所述,此函数确实返回一个具有惟一值的数组,但是问题要求查找重复项。在这种情况下,对这个函数进行简单的修改就可以将重复项推入数组,然后使用前面的函数来移除重复项的重复项。

function theDuplicates(a,b,c,d){//array,placeholder,placeholder
 b=a.length,d=[];
 while(c=--b)while(c--)a[b]!==a[c]||d.push(a.splice(c,1))
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];

toUnique(theDuplicates(array));

Var arr = [4,5,1,1,2,3,4,4,7,5,2,6,10,9]; Var sorted_arr = arr.sort(); Var len = arrr .length; Var结果= []; For (var I = 0;I < len;我+ +){ If (sorted_arr[i + 1] !== sorted_arr[i]) { results.push (sorted_arr[我]); } } document . write(结果);


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

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

类似于其他一些答案,但我使用forEach()使它更漂亮一点:

function find_duplicates(data) {

    var track = {};
    var duplicates = [];

    data.forEach(function (item) {
        !track[item] ? track[item] = true : duplicates.push(item);
    });

    return duplicates;
}

如果一个值被复制了不止一次,它的所有副本将被返回,如下所示:

find_duplicates(['foo', 'foo', 'bar', 'bar', 'bar']);
// returns ['foo', 'bar', 'bar']

这可能就是你想要的,否则你只能使用一个“唯一的”过滤。


更新:简短的一行程序,以获得副本:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]

要获得没有重复项的数组,只需反转条件:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]

注意,这个答案的主要目标是简短。如果你需要一个大数组的性能,一个可能的解决方案是先排序你的数组(如果它是可排序的),然后执行以下操作来获得与上面相同的结果:

myHugeSortedArray.filter((e, i, a) => a[i-1] === e)

下面是一个1 000 000个整数数组的例子:

const myHugeIntArrayWithDuplicates =
  [...Array(1_000_000).keys()]
  // adding two 0 and four 9 duplicates
  .fill(0, 2, 4).fill(9, 10, 14)

console.time("time")
console.log(
  myHugeIntArrayWithDuplicates
  // a possible sorting method for integers
  .sort((a, b) => a > b ? 1 : -1)
  .filter((e, i, a) => a[i-1] === e)
)
console.timeEnd("time")

在我的AMD Ryzen 7 5700G开发机上输出:

[ 0, 0, 9, 9, 9, 9 ]
time: 22.738ms

正如在评论中指出的那样,短解决方案和性能解决方案都将返回一个具有多次相同副本的数组,如果它在原始数组中出现多次:

[1, 1, 1, 2, 2, 2, 2].filter((e, i, a) => a.indexOf(e) !== i) // [1, 1, 2, 2, 2]

如果需要唯一的副本,则函数为

function duplicates(arr) {
  return [...new Set(arr.filter((e, i, a) => a.indexOf(e) !== i))]
}

可以使用duplicate([1, 1, 1, 2, 2, 2, 2])返回[1,2]。


当你所需要的只是检查是否像这个问题中要求的那样没有重复时,你可以使用every()方法:

[1, 2, 3].every((e, i, a) => a.indexOf(e) === i) // true

[1, 2, 1].every((e, i, a) => a.indexOf(e) === i) // false

注意,every()在ie8及以下版本中不起作用。


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

Var arr = [2,1,2,2,4,4,2,5]; 函数returnduplicate (arr) { 加勒比海盗。Reduce(函数(dupes, val, i) { 如果(arr.indexOf (val) ! = =我& & dupes.indexOf (val) = = = 1) { dupes.push (val); } 返回欺骗; },[]); } alert (returnDuplicates (arr));

这个函数避免了排序步骤,并使用reduce()方法将重复项推入一个新数组(如果该数组中不存在)。


以O(n)时间复杂度(不排序)求解上述问题。

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];

var obj={};

for(var i=0;i<arr.length;i++){
    if(!obj[arr[i]]){
        obj[arr[i]]=1;
    } else {
        obj[arr[i]]=obj[arr[i]]+1;
    }
}
var result=[]
for(var key in obj){
    if(obj[key]>1){
        result.push(Number(key)) // change this to result.push(key) to find duplicate strings in an array
    }
}

console.log(result)

在数组中查找重复的值

这应该是在数组中找到重复值的最短方法之一。正如OP特别要求的那样,这不会删除重复项,而是找到它们。

Var输入= [1,2,3,1,3,1]; Var duplicate =输入。Reduce(函数(acc, el, i, arr) { if (arr.indexOf(el) !== i && ac . indexof (el) < 0) ac .push(el);返回acc; },[]); document . write(副本);// = 1,3(实际数组= [1,3])

这不需要排序或任何第三方框架。它也不需要手动循环。它适用于indexOf()(或者更清楚地说:严格比较运算符)支持的所有值。

因为reduce()和indexOf(),它至少需要ie9。


下面是一个简单的小片段,用于查找唯一的和重复的值,无需排序和两个循环。

Var _unique =函数(arr) { Var h = [], t = []; 加勒比海盗。forEach(函数(n) { if (h.indexOf(n) == -1) h.push (n); 其他t.push (n); }); 返回[h, t]; } var =结果_unique([“测试”,1 4 2,34岁,6日,21日,3,4,“测试”、“王子”、“th”,34]); console.log("Has duplicate values: " + (result[1]. log)长度> 0))//你可以检查重复值的计数 Console.log (result[0]) //唯一值 Console.log (result[1]) //重复值


使用“includes”测试元素是否已经存在。

Var arr = [1,1,4,5,5], darr = [], duplicate = []; For (var I = 0;I < arrr .length;我+ +){ If (darr.includes(arr[i]) && !重复。includes(arr[i])) duplicates.push (arr[我]) 其他的 darr.push (arr[我]); } console.log(副本); <h3>重复数组</h3> <p>[1,1,4,5,5]</p> <h3>具有不同元素的数组</h3> <p>[1,4,5]</p> <h3>重复值</h3> (1、5)< p > < / p >


function GetDuplicates(arr) {
    var i = 0, m = [];
    return arr.filter(function (n) {
        return !m[n] * ~arr.indexOf(n, m[n] = ++i);
    });
}

ES6提供了Set数据结构,它基本上是一个不接受重复的数组。 使用Set数据结构,有一种非常简单的方法来查找数组中的重复项(只使用一个循环)。

这是我的代码

function findDuplicate(arr) {
var set = new Set();
var duplicates = new Set();
  for (let i = 0; i< arr.length; i++) {
     var size = set.size;
     set.add(arr[i]);
     if (set.size === size) {
         duplicates.add(arr[i]);
     }
  }
 return duplicates;
}

var a= [1, 2,2,3,3,4,4,4];
var m=[];
var n = [];
a.forEach(function(e) {
  if(m.indexOf(e)=== -1) {
    m.push(e);
}else if(n.indexOf(e)=== -1){
    n.push(e);
}

});

你可以使用下面的结构:

var arr = [1,2,3,4,5,6,7,8,9,0,5];
var duplicate = arr.filter(function(item, i, arr) {
  return -1 !== arr.indexOf(item, i + 1);
})

我觉得最简单的解决方案就是使用indexOf

仅将唯一元素推入数组的完整示例。

var arr = ['a','b','c','d','a','b','c','d'];
var newA = [];
for(var i = 0; i < arr.length; i++){
    if(newA.indexOf(arr[i]) === -1){
        newA.push(arr[i]);
    }
 }

使用Pure Js

function arr(){
  var a= [1,2,3,4,5,34,2,5,7,8,6,4,3,25,8,34,56,7,8,76,4,23,34,46,575,8564,53,5345657566];
  var b= [];
  b.push(a[0]);
  var z=0;

  for(var i=0; i< a.length; i++){
      for(var j=0; j< b.length; j++){
        if(b[j] == a[i]){
          z = 0;
          break;
        }
        else
          z = 1;
      }
      if(z)
        b.push(a[i]);
    }
  console.log(b);
}

var isUnique = true;      
for (var i= 0; i< targetItems.length; i++) {
        var itemValue = $(targetItems[i]).val();
        if (targetListValues.indexOf(itemValue) >= 0) {
          isUnique = false;
           break;
        }
      targetListValues.push(itemValue);
        if (!isUnique) {
          //raise any error msg
          return false;
        }
      }

使用ES6(或使用Babel或Typescipt),你可以简单地做:

var duplicates = myArray.filter(i => myArray.filter(ii => ii === i).length > 1);

https://es6console.com/j58euhbt/


最快的解决方法是用一面旗子

Var值= [4,2,3,1,4] / /解决方案 const checkDuplicate = list => { var hasDuplicate = false; list.sort()。排序((a, b) => { if (a == b) hasDuplicate = true }) 返回hasDuplicate } console.log (checkDuplicate(值))


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

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(副本);


这也可以使用Set()来解决。

Set中的一个值只能出现一次;在Set的收藏中是独一无二的。

    Array.prototype.hasDuplicates = function () {
        if (arr.length !== (new Set(arr).size)) {
            return true;
        }
        return false;
    }

更多关于集合的信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

注意:IE中不完全支持集合。


在这里,每个dupe只输出一次副本。

Var arr = [9,9,9,9,111, 2,3,4,4,5,7]; arr.sort (); Var结果= []; For (var I = 0;我< arr。长度- 1;我+ +){ 如果(arr[i + 1] == arr[i]) { results.push (arr[我]); } } results = Array.from(new Set(results)) console.log(结果);


ES6语法的简单代码(返回重复的排序数组):

let duplicates = a => {d=[]; a.sort((a,b) => a-b).reduce((a,b)=>{a==b&&!d.includes(a)&&d.push(a); return b}); return d};

使用方法:

duplicates([1,2,3,10,10,2,3,3,10]);

这是我能想到的最简单的ES5解决方案之一

function duplicates(arr) {
  var duplicatesArr = [],
      uniqueObj = {};

  for (var i = 0; i < arr.length; i++) {
    if( uniqueObj.hasOwnProperty(arr[i]) && duplicatesArr.indexOf( arr[i] ) === -1) {
      duplicatesArr.push( arr[i] );
    }
    else {
      uniqueObj[ arr[i] ] = true;
    }
  }

  return duplicatesArr;
}
/* Input Arr: [1,1,2,2,2,1,3,4,5,3] */
/* OutPut Arr: [1,2,3] */

简单的一行方式

Var arr = [9,1,2,4,3,4,9] console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //获取副本 console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //删除重复项


这是基于出现次数的更高级的函数。

function getMostDuplicated(arr, count) {
      const result = [];
      arr.forEach((item) => {
        let i = 0;
        arr.forEach((checkTo) => {
          if (item === checkTo) {
            i++;
            if (i === count && result.indexOf(item) === -1) {
              result.push(item);
            }
          }
        });
      });
      return result;
}

arr = [1,1,1,2,5,67,3,2,3,2,3,1,2,3,4,1,4];
result = getMostDuplicated(arr, 5); // result is 1
result = getMostDuplicated(arr, 2); // result 1, 2, 3, 4
console.log(result);

遵循逻辑会更容易、更快

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


快速和优雅的方式使用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']


//find duplicates: //sort, then reduce - concat values equal previous element, skip others //input var a = [1, 2, 3, 1, 2, 1, 2] //short version: var duplicates = a.sort().reduce((d, v, i, a) => i && v === a[i - 1] ? d.concat(v) : d, []) console.log(duplicates); //[1, 1, 2, 2] //readable version: var duplicates = a.sort().reduce((output, element, index, input) => { if ((index > 0) && (element === input[index - 1])) return output.concat(element) return output }, []) console.log(duplicates); //[1, 1, 2, 2]


打印重复值

var arr = [1,2,3,4,13,2,3,4,3,4]; // non_unique Printing function nonUnique(arr){ var result = []; for(var i =0;i<arr.length;i++){ if(arr.indexOf(arr[i],i+1) > -1){ result.push(arr[i]); } } console.log(result); }nonUnique(arr); // unique Printing function uniqueDuplicateVal(arr){ var result = []; for(var i =0;i<arr.length;i++){ if(arr.indexOf(arr[i],i+1) > -1){ if(result.indexOf(arr[i]) === -1]){ result.push(arr[i]); } } } } uniqueDuplicateVal(arr)


这是我的简单和一行解决方案。

它首先搜索不是唯一的元素,然后使用Set使所找到的数组是唯一的。

最后我们有一个重复的数组。

Var数组= [1,2,2,3,3,4,5,6,2,3,7,8,5,22,1,2,511,12,50,22]; console.log([…新设置( 数组中。filter((value, index, self) => self. indexof (value) !== index))] );


这是我用map实现的。它应该运行在O(n)时间,应该有点容易喘气。

var first_array = [1, 1, 2, 3, 4, 4, 5, 6); var find_dup=new Map; For (first_array的const迭代器){ //如果现值++ 如果(find_dup.has (iterator)) { find_dup.set(迭代器,find_dup.get(迭代器)+ 1); 其他}{ //否则添加 find_dup.set(迭代器,1); } } console.log (find_dup.get (2));

然后你可以find_dup.get(key)来查找它是否有重复(它应该给> 1)。


这是我的建议(ES6):

let a = [1, 2, 3, 4, 2, 2, 4, 1, 5, 6]
let b = [...new Set(a.sort().filter((o, i) => o !== undefined && a[i + 1] !== undefined && o === a[i + 1]))]

// b is now [1, 2, 4]

这应该是在数组中查找重复值的最短和最简单的方法之一。

Var arr = [1,2,3,4,5,6,7,8,1,2,3,4,5,3,4]; Var数据= arr.filter(函数(项目,索引,arr){ 返回arr.indexOf(item) != arr.lastIndexOf(item) && arr.indexOf(item) == index; }) console.log(数据);


你可以通过比较index:

function getDuplicate(array) {
    return array.filter((value, index) => array.value !== index)
}

返回副本并保留数据类型。

具有O(4n)性能

const dupes = arr => {
  const map = arr.reduce((map, curr) => {
    return (map.set(curr, (map.get(curr) || 0) + 1), map)
  }, new Map());

  return Array.from(map).filter(([key, val])=> val > 1).map(([key, val]) => key)
}

具有O(2n)性能

const dupes = arr => {
  const map = arr.reduce((map, curr) => {
    return (map.set(curr, (map.get(curr) || 0) + 1), map)
  }, new Map());

  const dupes_ = [];
  for (let [key, val] of map.entries()) {
    if (val > 1) dupes_.push(key);
  }
  return dupes_;
}

这是我能想到的最有效的方法,因为不包括Array.indexOf()或Array.lastIndexOf(),它们的复杂度为O(n),并且在复杂度为O(n)的任何循环中使用将使完整的复杂度为O(n²)。

我的第一个循环的复杂度是O(n/2)或O((n/2) + 1),因为在哈希中搜索的复杂度是O(1)。当数组中没有重复元素时,第二个循环的最差复杂度为O(n),当每个元素都有重复元素时,最佳复杂度为O(n/2)。

function duplicates(arr) {
  let duplicates = [],
      d = {},
      i = 0,
      j = arr.length - 1;

  // Complexity O(n/2)
  while (i <= j) {
    if (i === j)
      d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1;  // Complexity O(1)
    else {
      d[arr[i]] ? d[arr[i]] += 1 : d[arr[i]] = 1;  // Complexity O(1)
      d[arr[j]] ? d[arr[j]] += 1 : d[arr[j]] = 1;  // Complexity O(1)
    }

    ++i;
    --j;
  }

  // Worst complexity O(n), best complexity O(n/2)
  for (let k in d) {
    if (d[k] > 1)
      duplicates.push(k);
  }

  return duplicates;

}

console.log(duplicates([5,6,4,9,2,3,5,3,4,1,5,4,9]));
console.log(duplicates([2,3,4,5,4,3,4]));
console.log(duplicates([4,5,2,9]));
console.log(duplicates([4,5,2,9,2,5,9,4]));

魔法

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


这是一种单循环方法,使用哈希表来计数元素,如果计数为2则过滤数组,因为它返回第一个找到的重复元素。

优势:

单回路 在闭包中使用对象进行计数

数组var =[5 0、2、1、2、3、3、4、4、8、6、7、9,4], duplicate = array。过滤器((h = > v = > (h [v] = (h [v] | | 0) + 1) = = = 2) ({})); console.log(副本);


我们将使用Javascript ES6功能来做魔术!

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
const filtered = arr.filter((value, index) => {
 return arr.indexOf(value) >= index;
});

console.log(filtered);

https://jsfiddle.net/97Lxupnz/


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

函数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]));


这将从数组中返回副本作为副本数组。

Const duplicate = function(arr) { //让我们试着两人一组。也许会有用 let dups = new Set(), R = [] arr.sort () 加勒比海盗。Reduce ((pv, cv) => { If (pv === cv) { dups.add (pv) } 返回的简历 }) For (let m of dpps .values()) { r.push (m) } 返回r } console.log(副本([1、3、5、6、7、4、4、5、1、4、6、3、8、9日5 0]))


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

arr.filter( (item , index ) => {  
console.log(item , index , arr.indexOf(item) , arr.indexOf( item ) == index);
return index == arr.indexOf(item)
 } );


这是我能想到的最简单的解决办法:

const arr =[1、2、2、2 0,0,0,500,1,“,”“,”“) Const filtered = arr。filter((el, index) => arr.indexOf(el) !== index) // => filtered = [2,2,0,0, -1, 'a', 'a'] Const duplicate =[…]新的(过滤) console.log(副本) // => [2,0, -1, 'a']

就是这样。

注意:

It works with any numbers including 0, strings and negative numbers e.g. -1 - Related question: Get all unique values in a JavaScript array (remove duplicates) The original array arr is preserved (filter returns the new array instead of modifying the original) The filtered array contains all duplicates; it can also contain more than 1 same value (e.g. our filtered array here is [ 2, 2, 0, 0, -1, 'a', 'a' ]) If you want to get only values that are duplicated (you don't want to have multiple duplicates with the same value) you can use [...new Set(filtered)] (ES6 has an object Set which can store only unique values)

希望这能有所帮助。


有一个非常简单的方法来解决这个问题。如果你使用新的'Set' javascript命令。Set可以接受一个数组作为输入,并输出一个只包含唯一值的新“Set”。然后通过比较数组的长度和集合的'size'属性,你可以看到它们是否不同。如果它们不同,一定是由于重复的条目。

Var array1 = ['value1','value2','value3','value1'];//包含重复项 Var array2 = ['value1','value2','value3','value4'];//唯一值 console.log('array1 contains duplicate = ' + containsduplicate (array1)); console.log('array2 contains duplicate = ' + containsduplicate (array2)); 函数containsduplicate (passedArray) { let mySet = new Set(passsedarray); 如果(mySet。size == passsedarray .length) { 返回true; } 返回错误; }

如果运行上面的代码片段,将得到以下输出。

Array1包含duplicate = true

Array2包含重复项= false


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

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


最短的香草JS:

[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]

你可以使用排序、筛选和集合来做到这一点。

Var数= [1,2,3,4,5,6,7,8,1,2,3,4,5,3,4]; var numbersSorted = numbers.sort(); 令result = numbers。Filter ((e, i) => numbers[i] == numbers[i+1]); 结果=[…]新设置(结果)]; console.log(结果);


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

排名较高的答案有一些固有的问题,包括使用遗留的javascript,不正确的排序或只支持2个重复的项目。

这里有一个解决这些问题的现代解决方案:

const arrayNonUniq = array => {
    if (!Array.isArray(array)) {
        throw new TypeError("An array must be provided!")
    }

    return array.filter((value, index) => array.indexOf(value) === index && array.lastIndexOf(value) !== index)
}

arrayNonUniq([1, 1, 2, 3, 3])
//=> [1, 3]

arrayNonUniq(["foo", "foo", "bar", "foo"])
//=> ['foo']

你也可以使用npm包array-non-uniq。


非常简单的方法:

函数getDuplicateValues(someArray) { const duplicateValues = new Set([]) const check = new Set([]) someArray。forEach(v => { If (check.has(v)) { duplicateValues.add (v) }其他{ check.add (v) } }) 返回Array.from (duplicateValues); } const result = getDuplicateValues(['咖啡','苏打','水','果汁','水','水','咖啡']) repeated_values。textContent = JSON。Stringify(结果,null, ' ') < pre id = " repeated_values " > < / >之前


基于@ 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']

公认的答案是最完美的,但正如一些用户指出的那样,对于一个元素重复超过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);

您可以使用filter方法和indexOf()来获取所有重复的值

function duplicate(arr) {
    return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index) 
}

arr.indexOf(item)将始终返回给定元素所在的第一个索引 发现


最简单快捷的方法是使用Set对象:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const set = new Set(numbers);

const duplicates = numbers.filter(item => {
    if (set.has(item)) {
        set.delete(item);
        return false;
    } else {
        return true;
    }
});

// OR more concisely

const duplicates = numbers.filter(item => !set.delete(item));

console.log(duplicates);
// [ 2, 5 ]

Const名称= [ “亚历克斯”, “马特”, 12日, “你”, “我”, 12, “颂歌”, “自行车”, “颂歌”, ]; Const count = (names) => 的名字。Reduce ((a, b) =>({…A, [b]: (A [b] || 0) + 1}), {}); 让obj = count(names); let objectKeys = Object.keys(obj); let repetitiveElements = []; let answer = objectKeys.map((value) => { 如果(obj[value] > 1) { 返回repetitiveElements.push(价值); } }); console.log (repetitiveElements);


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

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

带有注释的代码。

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


这个问题有这么多错误的答案,或者答案像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([]));

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

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

它的性能很好


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

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

[1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 50, 8, 5, 22, 1, 2, 511, 12, 50, 22].reduce(function (total, currentValue, currentIndex, arr) {
    if (total.indexOf(currentValue) === -1 && arr.indexOf(currentValue) !== currentIndex) 
        total.push(currentValue);
    return total;
}, [])

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

这是用ES6语法找到重复元素的最简单方法

Const arr =[1,2,3,3,21,3, 21,34] const duplicate = Array.from(new Set(arr. from)filter((例如,i, ar)=> i !==ar. indexof(例如)))) console.log(副本)


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

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

打印稿

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

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

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