Search code examples
javascriptarrayslodash

lodash: Get duplicate values from an array


Say I have an array like this: [1, 1, 2, 2, 3]

I want to get the duplicates which are in this case: [1, 2]

Does lodash support this? I want to do it in the shortest way possible.


Solution

  • You can use this:

    _.filter(arr, (val, i, iteratee) => _.includes(iteratee, val, i + 1))
    

    or without using lodash, you can use plain JavaScript:

    arr.filter((val, i) => arr.includes(val, i + 1))
    

    Note: that if a number appears more than two times in your array you can always use _.uniq.