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
.
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. }
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With