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

后端 未结 30 3302
再見小時候
再見小時候 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:37

    Fast and elegant way using es6 object destructuring and reduce

    It runs in O(n) (1 iteration over the array) and doesn't repeat values that appear more than 2 times

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

提交回复
热议问题