Categories
JavaScript Answers

How to Get Duplicate Values from an Array with Lodash?

Spread the love

Sometimes, we want to get duplicate values from an array with Lodash.

In this article, we’ll look at how to get duplicate values from an array with Lodash.

Get Duplicate Values from an Array with Lodash

To get duplicate values from an array with Lodash, we can use the countBy method to count the values.

Then we call the JavaScript array’s reduce method to get all the items that has count more than 1 and put them in an array.

For instance, we write:

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

const dup = Object.entries(_.countBy(items))
  .reduce((acc, [key, val]) => {
    return val > 1 ? acc.concat(key) : acc
  }, [])
  .map(Number)

console.log(dup)

We call the countBy method with items to return an object with the count of each item in the items array.

Then we call Object.entries to return an array of key-value pairs in the object returned by countBy.

Next, we call reduce with a callback that takes the acc array and the destructured key and val from the each array returned by Object.entries.

If val is bigger than 1, then we know there’s more than one item with the given key.

So we put the in acc with concat.

Otherwise, we return acc without appending the entry since there’s only one instance of the val value.

We pass in an empty array as the value of the 2nd argument so acc is initialized to an empty array.

Finally, we call map with Number to convert all the entries back to numbers.

Therefore dup is [1, 3, 7] according to the console log.

Conclusion

To get duplicate values from an array with Lodash, we can use the countBy method to count the values.

Then we call the JavaScript array’s reduce method to get all the items that has count more than 1 and put them in an array.

Leave a Reply

Your email address will not be published. Required fields are marked *