获取数组中的所有非唯一值(即:重复/多次出现)

Sco*_*ers 397 javascript arrays

我需要检查一个JavaScript数组,看看是否有任何重复的值.最简单的方法是什么?我只需要找到重复的值是什么 - 我实际上并不需要它们的索引或重复它们的次数.

我知道我可以遍历数组并检查匹配的所有其他值,但似乎应该有一个更简单的方法.有任何想法吗?谢谢!

类似的问题:

swi*_*ams 282

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

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var 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)
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}

console.log(results);
Run Code Online (Sandbox Code Playgroud)

  • 这个脚本不能很好地处理超过2个重复项(例如`arr = [9,9,9,111,2,3,3,3,4,4,5,7]; (77认同)
  • -1这个答案在很多层面都是错误的.首先`var sorted_arr = arr.sort()`是没用的:`arr.sort()`改变原始数组(这本身就是一个问题).这也丢弃了一个元素.(运行上面的代码.9会发生什么?)cc @dystroy一个更干净的解决方案是`results = arr.filter(function(elem,pos){return arr.indexOf(elem)== pos;})` (32认同)
  • 每个人:问题要求显示重复值,而不是删除它们.请不要编辑/破坏代码以试图让它做一些它不想做的事情.警报应显示重复的值. (22认同)
  • "假设您的排序算法很好,这应该小于O ^ 2".具体来说,它可以是O(n*log(n)). (9认同)
  • @swilliams我不认为这些指导方针说不使用`i ++`.相反,他们说不要写'j = i + + j`.恕我直言的两件事.我认为`i + = 1`比简单而美丽的`i ++` :)更令人困惑 (7认同)
  • @danilo我知道,虽然我倾向于遵循Crockford关于不在JS中使用该模式的建议.http://javascript.crockford.com/code.html (3认同)

rap*_*ria 204

如果您想要重复删除重复项,请尝试以下解决方案:

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

  for (i = 0; i < len; i++) {
    obj[arr[i]] = 0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 上面的代码(这是我的 - 这是我的博客)让你非常接近.一个小小的调整,你就在那里.首先,您可以看到arr.length和out.length是否相同.如果它们相同,则没有重复的元素.但是你想多一点.如果你想在发生时"捕获"欺骗,检查obj [arr [i]] = 0行后数组的长度是否增加.好漂亮,嗯?:-)感谢好听的拉斐尔蒙塔纳罗. (66认同)
  • 这是很好的代码,但遗憾的是它不能满足我的要求. (17认同)
  • @MarcoDemaio:呃,不,为什么代码不能用空格?您可以在属性名称中放置任何您喜欢的内容 - 只是不能使用点语法来访问带有空格的那些(也不能使用会破坏解析的各种其他字符的道具). (6认同)
  • @Gijs:+1你是对的.我不知道.但是当它是一个对象数组时它仍然不起作用. (4认同)
  • 此算法还具有返回已排序数组的副作用,这可能不是您想要的. (3认同)
  • 你想要一个*真正*优雅的方式来删除重复?试试这个班轮:http://stackoverflow.com/a/9229821/396458 (2认同)

Chr*_*ren 160

这是我从重复的线程(!)得到的答案:

厌倦了看到所有使用for循环或jQuery的坏例子.Javascript现在拥有完美的工具:排序,映射和缩小.

找到重复的项目

var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']

var uniq = names
  .map((name) => {
    return {
      count: 1,
      name: name
    }
  })
  .reduce((a, b) => {
    a[b.name] = (a[b.name] || 0) + b.count
    return a
  }, {})

var duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1)

console.log(duplicates) // [ 'Nancy' ]
Run Code Online (Sandbox Code Playgroud)

更多功能语法:

@ Dmytro-Laptin指出要删除一些代码.这是相同代码的更紧凑版本.使用一些ES6技巧和更高阶函数:

const names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']

const count = names =>
  names.reduce((a, b) => ({ ...a,
    [b]: (a[b] || 0) + 1
  }), {}) // don't forget to initialize the accumulator

const duplicates = dict =>
  Object.keys(dict).filter((a) => dict[a] > 1)

console.log(count(names)) // { Mike: 1, Matt: 1, Nancy: 2, Adam: 1, Jenny: 1, Carl: 1 }
console.log(duplicates(count(names))) // [ 'Nancy' ]
Run Code Online (Sandbox Code Playgroud)

使用Function.prototype.bind:

var names = ['Mike', 'Matt', 'Nancy', 'Adam', 'Jenny', 'Nancy', 'Carl']

var uniq = names
  .map((name) => {
    return {
      count: 1,
      name: name
    }
  })
  .reduce((a, b) => {
    a[b.name] = (a[b.name] || 0) + b.count
    return a
  }, {})

var duplicates = Object.keys(uniq).filter((a) => uniq[a] > 1)

console.log(duplicates) // [ 'Nancy' ]
Run Code Online (Sandbox Code Playgroud)

  • 请自己保留您的误导性意见(自大为-1)。我个人讨厌人们混淆“简短”和“高效”,并且张贴单行而不质疑表演。短程序和现代JS本质上并不是更好。“效率”一词的典型误用[此处](/sf/ask/58854701/#comment64457920_24968449)。典型的天真信念[here](/sf/ask/58854701/#comment24098875_840849)(请阅读以下评论)。演示[此处](/sf/answers/3838489511/)。 (4认同)

flu*_*flu 53

在数组中查找重复值

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

var input = [1, 2, 3, 1, 3, 1];

var duplicates = input.reduce(function(acc, el, i, arr) {
  if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
}, []);

document.write(duplicates); // = 1,3 (actual array == [1, 3])
Run Code Online (Sandbox Code Playgroud)

这不需要排序或任何第三方框架.它也不需要手动循环.它适用于每个值indexOf()(或更清晰:严格的比较运算符)支持.

由于reduce()indexOf(),它至少需要IE 9.

  • ES6箭头/简单/纯版本:`const dupes = items.reduce((acc,v,i,arr)=&gt; arr.indexOf(v)!== i &amp;&amp; acc.indexOf(v)=== -1? acc.concat(v):acc,[])` (5认同)

kar*_*m79 30

您可以添加此功能,或调整它并将其添加到Javascript的Array原型中:

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);
Run Code Online (Sandbox Code Playgroud)

  • 不执行 OP 要求的操作,返回重复项。 (3认同)

小智 27

更新:以下使用优化的组合策略.它优化了原始查找以受益于散列O(1)查找时间(unique在基元数组上运行是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;
}();
Run Code Online (Sandbox Code Playgroud)

如果您有可用的ES6集合,则可以使用更简单且速度更快的版本.(这里是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;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为不同的解决方案很好.这个主题是旧的并且解决了并不重要,因为它仍然可以提出不同的方法来做到这一点.这是计算机科学中的典型问题. (16认同)
  • 我正在回答另一个问题,显然是偶然点击了链接到这个问题的人,称之为复制品,最后克隆了我的答案,让我自己感到困惑.我编辑了很多东西. (3认同)

Dan*_*ley 17

这应该得到你想要的,只是重复.

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.
Run Code Online (Sandbox Code Playgroud)


Ang*_*ott 17

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

a.filter(function(value,index,self){ return (self.indexOf(value) !== index )})
Run Code Online (Sandbox Code Playgroud)

  • 如果重复值出现 2 次以上,则不起作用。 (3认同)

att*_*ian 15

最简单、最快的方法是使用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 ]
Run Code Online (Sandbox Code Playgroud)


Lau*_*yot 14

当您只需检查此问题中没有重复项时,您可以使用以下filter()方法:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) !== i) // [2, 4]
Run Code Online (Sandbox Code Playgroud)

请注意,这every()不适用于IE 8及更低版本.

我使用every()它是因为它可能比在索引顺序中进行的filter()函数回调更有效every(),但是没有证明.

CoffeeScript中我使用这个:

[1, 2, 2, 4, 3, 4].filter((e, i, a) => a.indexOf(e) === i) // [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

  • @Wajahath 确实如此,感谢您指出这一点。如果需要唯一的重复项,则可以使用类似 `f = arr =&gt; [...new Set(arr.filter((e, i, a) =&gt; a.indexOf(e) !== i))]` 的函数使用“f([1, 1, 1, 2, 2, 2, 2])”返回“[1, 2]” (6认同)
  • 不执行 OP 要求的操作,返回重复项。 (5认同)
  • 请记住:`[2,2,2,2].filter((e, i, a) =&gt; a.indexOf(e) !== i)`给出`[2, 2, 2]` (2认同)

小智 13

使用underscore.js

function hasDuplicate(arr){
    return (arr.length != _.uniq(arr).length);
}
Run Code Online (Sandbox Code Playgroud)


sra*_*nji 7

一个班轮简单的方法

var arr = [9,1,2,4,3,4,9]
console.log(arr.filter((ele,indx)=>indx!==arr.indexOf(ele))) //get the duplicates
console.log(arr.filter((ele,indx)=>indx===arr.indexOf(ele))) //remove the duplicates
Run Code Online (Sandbox Code Playgroud)

  • @saylestyler 呵呵,这意味着 `indx !== ...` - 严格的不平等。 (2认同)

Ole*_*aev 7

这是我的简单和一线解决方案.

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

所以我们最后有一系列重复.

var array = [1, 2, 2, 3, 3, 4, 5, 6, 2, 3, 7, 8, 5, 22, 1, 2, 511, 12, 50, 22];

console.log([...new Set(
  array.filter((value, index, self) => self.indexOf(value) !== index))]
);
Run Code Online (Sandbox Code Playgroud)


Nik*_*vic 7

这是我能想到的最简单的解决方案:

const arr = [-1, 2, 2, 2, 0, 0, 0, 500, -1, 'a', 'a', 'a']

const filtered = arr.filter((el, index) => arr.indexOf(el) !== index)
// => filtered = [ 2, 2, 0, 0, -1, 'a', 'a' ]

const duplicates = [...new Set(filtered)]

console.log(duplicates)
// => [ 2, 0, -1, 'a' ]
Run Code Online (Sandbox Code Playgroud)

就是这样。

笔记:

  1. 它适用于任何数字,包括0、字符串和负数,例如-1- 相关问题: 获取 JavaScript 数组中的所有唯一值(删除重复项)

  2. arr保留原始数组(filter返回新数组而不是修改原始数组)

  3. filtered数组包含所有重复项;它还可以包含 1 个以上的相同值(例如,我们这里的过滤数组是[ 2, 2, 0, 0, -1, 'a', 'a' ]

  4. 如果你想获得是重复的值(你不希望有相同值的多个副本),可以使用[...new Set(filtered)](ES6都有一个对象可存储唯一的值)

希望这可以帮助。


vsy*_*ync 6

从3个数组(或更多)中查找唯一值:

Array.prototype.unique = function () {
    var arr = this.sort(), i; // input must be sorted for this to work
    for( i=arr.length; i--; )
      arr[i] === arr[i-1] && arr.splice(i,1); // remove duplicate item

    return arr;
}

var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,9],
    arr2 = [1,2,511,12,50],
    arr3 = [22],
    unique = arr.concat(arr2, arr3).unique();

console.log(unique);  // [22, 50, 12, 511, 2, 1, 9, 5, 8, 7, 3, 6, 4]
Run Code Online (Sandbox Code Playgroud)

只是旧浏览器的数组indexOf的polyfill:

if (!Array.prototype.indexOf){
   Array.prototype.indexOf = function(elt /*, from*/){
     var len = this.length >>> 0;

     var from = Number(arguments[1]) || 0;
     from = (from < 0) ? Math.ceil(from) : Math.floor(from);
     if (from < 0)
        from += len;

     for (; from < len; from++){
        if (from in this && this[from] === elt)
           return from;
     }
     return -1;
  };
}
Run Code Online (Sandbox Code Playgroud)

使用"inArray"的jQuery解决方案:

if( $.inArray(this[i], arr) == -1 )
Run Code Online (Sandbox Code Playgroud)

ES2015

var arr =  [1,2,2,3,3,4,5,6,2,3,7,8,5,22],
    arr2 = [1,2,511,12,50],
    arr3 = [22],
    unique;

// Combine all the arrays to a single one
unique = arr.concat(arr2, arr3);
// create a new (dirty) Array with only the unique items
unique = unique.map((item,i) => unique.includes(item, i+1) ? item : '' )
// Cleanup - remove duplicate & empty items items 
unique = [...new Set(unique)].filter(n => n);

console.log(unique);
Run Code Online (Sandbox Code Playgroud)

而不是添加'Array.prototype.indexOf'

  • 没有做OP要求的,返回重复. (2认同)

Lor*_*uer 6

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;});
Run Code Online (Sandbox Code Playgroud)

或者当添加到Array的prototyp.chain时

//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;});}
Run Code Online (Sandbox Code Playgroud)

见这里:https://gist.github.com/1305056


Luc*_*non 6

使用ES6对象分解和减少的快速而优雅的方式

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

const arr = ['hi', 'hi', 'hi', 'bye', 'bye', 'asd']
const {
  dup
} = arr.reduce(
  (acc, curr) => {
    acc.items[curr] = acc.items[curr] ? acc.items[curr] += 1 : 1
    if (acc.items[curr] === 2) acc.dup.push(curr)
    return acc
  }, {
    items: {},
    dup: []
  },
)

console.log(dup)
// ['hi', 'bye']
Run Code Online (Sandbox Code Playgroud)


luk*_*ups 6

This is my proposal (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]
Run Code Online (Sandbox Code Playgroud)


chi*_*ens 6

最短的香草JS

[1,1,2,2,2,3].filter((v,i,a) => a.indexOf(v) !== i) // [1, 2, 2]
Run Code Online (Sandbox Code Playgroud)


小智 5

You can use filter method and indexOf() to get all the duplicate values

function duplicate(arr) {
    return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index) 
}
Run Code Online (Sandbox Code Playgroud)

arr.indexOf(item) will always return the first index at which a given element can be found


归档时间:

查看次数:

545664 次

最近记录:

5 年,11 月 前