Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
zianwar Avatar asked Jul 28 '15 16:07

zianwar


People also ask

Does Lodash Uniq work on objects?

Lodash's 'uniq' family of methods can be implemented in plain JS without trouble. Lodash is a very useful utility library that lets us work with objects and arrays easily.

How do I remove duplicates in Lodash?

We can remove duplicate elements from an array using the _. uniq() method of Lodash. This method keeps the first instance of an element and removes the remaining one. Therefore, the order of an element in the resultant array depends on its occurrence in the array.

How do I compare two arrays in Lodash?

isEqual() Method. The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.


1 Answers

You can use this:

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

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

like image 117
saadel Avatar answered Sep 19 '22 12:09

saadel