Languages

JavaScript - get duplicate values from array using lodash

0 points
Asked by:
Aleena
694

How can I get duplicate values from an array using lodash?

Let's say I have an array like this:

var array = [1, 2, 3, 2, 3, 3];

and I want to get the duplicates, so the result in this case would be:

[2, 3]

Is there any lodash function to do this? I want to do it in the simplest possible way.

1 answer
0 points
Answered by:
Aleena
694

To get all duplicates from array you can use _.filter() combined with _.includes() method.

Then, to get unique duplicates from it you can use  _.uniq() method.

Practical example

In this example, we use lodash cdn to provide lodash library.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
  <script>

    var array = [1, 2, 3, 2, 3, 3];

    var allDuplicates = _.filter(array, function(value, index, iteratee) {
        return _.includes(iteratee, value, index + 1);
    });
    
    var uniqueDuplicates = _.uniq(allDuplicates);

    console.log(allDuplicates);    // [ 2, 3, 3 ]
    console.log(uniqueDuplicates); // [ 2, 3 ]

  </script>
</body>
</html>

 

See also

  1. JavaScript - find duplicates in array

References

  1. Lodash Documentation - _.filter()
  2. Lodash Documentation - _.includes()
  3. Lodash Documentation - _.uniq()
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join