Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

后端 未结 30 4044
再見小時候
再見小時候 2020-11-21 04:35

I need to check a JavaScript array to see if there are any duplicate values. What\'s the easiest way to do this? I just need to find what the duplicated values are - I don\'

30条回答
  •  庸人自扰
    2020-11-21 05:21

    This is my answer from the duplicate thread (!):

    When writing this entry 2014 - all examples were for-loops or jQuery. Javascript has the perfect tools for this: sort, map and reduce.

    Find duplicate items

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

    More functional syntax:

    @Dmytro-Laptin pointed out some code code be removed. This is a more compact version of the same code. Using some ES6 tricks and higher order functions:

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

提交回复
热议问题