If you have an array with primitive values as per below;
const arr = [1, 2, 3, 4, 45, 4, 66, 3];
Is there a more efficient way to check whether all the items are unique rather than iterating all items as below?
let newArr = [];
let isUnique = true;
arr.forEach(item =>
{
if(newArr.indexOf(item) != -1)
{
isUnique = false;
break;
}
newArray.push(item);
});
asked Oct 17, 2020 at 2:53
1 Answer 1
An indexOf
in a forEach
is O(n ^ 2)
. I'd use a Set instead - Set.has
is O(1)
(overall complexity of O(n)
):
const allAreUnique = (arr) => {
const set = new Set();
for (const item of arr) {
if (set.has(item)) return false;
set.add(item);
}
return true;
};
const allAreUnique = (arr) => {
const set = new Set();
for (const item of arr) {
if (set.has(item)) return false;
set.add(item);
}
return true;
};
console.log(allAreUnique([1, 2, 3, 4, 45, 4, 66, 3]));
console.log(allAreUnique([1, 2, 3, 4, 45, 66]));
answered Oct 17, 2020 at 2:54
4 Comments
Sam Sirry
Looks like the return is always
true
. The question requires knowing whether all the items are unique.Michael Geary
@SamSirry The code looks correct to me. If you run the snippet the first test returns
false
as expected.Christie
Thank you @CertainPerformance for the prompt answer. Appreciate it!
Sam Sirry
Sorry, I misread the code. Probably something was wrong with morning coffee... Thank you for your insight @MichaelGeary
lang-js