EN
JavaScript - get duplicate values from array using lodash
1
answers
0
points
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
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
References
0 comments
Add comment