patternjavascriptMinor
A function that checks for duplicate elements in an array
Viewed 0 times
checkselementsarrayduplicatefunctionthatfor
Problem
Is there a simpler way to implement this function?
function has_duplicates(arr) {
var myObject = {};
for (var key in arr) {
if (myObject[arr[key]])
return true;
else
myObject[arr[key]] = true;
}
return false;
}
console.log(has_duplicates(["foo", "bar", "baz", "quux", "foo"]));Solution
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;
}Code Snippets
function has_duplicates(arr) {for (var key in arr) {function hasDuplicates(arr){
return !!arr.filter(fuction(value){
return arr.indexOf(value) !== arr.lastIndexOf(value);
}).length;
}function hasDuplicates(arr){
var set = new Set();
arr.forEach(function(value){ set.add(value); });
return set.size !== arr.length;
}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;
}Context
StackExchange Code Review Q#104967, answer score: 6
Revisions (0)
No revisions yet.