Using lodash to check whether an array has duplicate values
Well, there's always. lodash's _.uniq() function. That function actually returns a new array that only contains unique values, so checking to see if the length of the array has changed would get you your 'true' or 'false' value to return yourself, I believe.
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.
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>
You could check that there is _.some
element in the array which does not return its own location when looked up in the array. In other words, there is at least one element which has a match earlier in the array.
function hasDuplicates(array) {
return _.some(array, function(elt, index) {
return array.indexOf(elt) !== index;
});
}
Perhaps this is faster than the _.uniq
solution, since it will identify the first duplicated element right away without having to compute the entire unique-ified array.
Or, depending on your coding style and desire for readability, and if you want to use ES6 arrow functions for brevity:
var earlierMatch = (elt, index, array) => array.indexOf(elt) !== index;
var hasDuplicates = array => _.some(array, earlierMatch);