function has_duplicates(arr) {
In JS, function names are usually in camelCase. So this should be hasDuplicates
.
for (var key in arr) {
Don't use for-in
with arrays. for-in
loops will run through properties, including prototype properties. Use a regular for
loop with counters. A forEach
would also work, but you can't bail out in the middle of the array.
So far, iirc, a loop and hash is favorable in this scenario since it's just O(n)
and you can bail out in the middle of the operation.
Another way to do it is the following. The concept is that when a value appears twice, indexOf
and lastIndexOf
will not be the same, thus adding the entry to the array created by filter
.
function hasDuplicates(arr){
return !!arr.filter(fuction(value){
return arr.indexOf(value) !== arr.lastIndexOf(value);
}).length;
}
Another way to do it is by using ES6's Set
. The concept is that sets only hold unique values. When you try to add a duplicate, it won't be added to the set. If there is a mismatch in the array length and set size, you jumped over a duplicate somewhere, thus revealing the existence of the duplicate.
function hasDuplicates(arr){
var set = new Set();
arr.forEach(function(value){ set.add(value); });
return set.size !== arr.length;
}
Going with @PeterCordes's suggestion, you can use Set
and check on each iteration the size mismatch. We can assume false
until a mismatch happens.
function hasDuplicates(arr){
var set = new Set();
for(var i = 0; i < arr.length; i++){
set.add(arr[i]);
if(set.size !== i + 1) return true;
}
return false;
}