Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lodash to check whether an array has duplicate values

What do you all think would be the best (best can be interpreted as most readable or most performant, your choice) way to write a function using the lodash utilities in order to check an array for duplicate values.

I want to input ['foo', 'foo', 'bar'] and have the function return true. And input ['foo', 'bar', 'baz'] and have the function return false.

like image 488
nackjicholson Avatar asked Feb 11 '15 17:02

nackjicholson


People also ask

How do I check if an array contains duplicate numbers?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = i+1; j < myArray. length; j++) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } return false; // means there are no duplicate values. }

How can you tell if an array is unique?

Better Solution: Use HashSet: Create a HashSet from the given array. Since Set does not contains duplicates, if original array has any duplicates, the size of HashSet will not be equal to the size of array and if size matches then array has all unique elements.

How do you remove duplicates in array of objects 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.


2 Answers

You can try this code:

function hasDuplicates(a) {    return _.uniq(a).length !== a.length;   }    var a = [1,2,1,3,4,5];  var b = [1,2,3,4,5,6];    document.write(hasDuplicates(a), ',',hasDuplicates(b));
<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.1.0/lodash.min.js"></script>
like image 84
agershun Avatar answered Sep 18 '22 12:09

agershun


As of ES6 you can simply use Set so this becomes:

let hasDuplicates = arr => new Set(arr).size != arr.length    console.log(hasDuplicates([5,3,2,1,2,1,2,1]))  console.log(hasDuplicates([1,2,3,4,5]))

Which somewhat negates the use of lodash in this particular case.

like image 31
Akrion Avatar answered Sep 18 '22 12:09

Akrion