To check if an array has duplicates, you can combine the some()
function and an empty object:
javascriptlet hasDuplicates = ['a', 'b', 'a'].some(e => { if(o[e]){ // If the element exists in the object, return true // The some function will break after this line return true; } else{ // If the element doesn't exist, create it o[e] = true; // The some function will continue after this line // on returning false return false; } }, o = {});
In one line of code:
javascriptlet hasDuplicates = ['a', 'b', 'a'].some(e => o[e] ? true : (o[e] = true, false), o = {}); // true
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.