Categories
JavaScript Answers Lodash

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.

How to get duplicate values from an array with Lodash?

To get duplicate values from an array with Lodash, we can use the filter and includes methods.

For instance, we write:

const arr = [1, 2, 2, 3, 3]
const dups = _.filter(arr, (val, i, iteratee) => _.includes(iteratee, val, i + 1));

console.log(dups)

We have an arr array that has some duplicate values.

Then we call filter with arr and a callback that calls includes to check if the array has the duplicate entries of val.

Therefore, dups is [2, 3].

Conclusion

To get duplicate values from an array with Lodash, we can use the filter and includes methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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