2

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);
});

1 Answer 1

4

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]));

Sign up to request clarification or add additional context in comments.

4 Comments

Looks like the return is always true. The question requires knowing whether all the items are unique.
@SamSirry The code looks correct to me. If you run the snippet the first test returns false as expected.
Thank you @CertainPerformance for the prompt answer. Appreciate it!
Sorry, I misread the code. Probably something was wrong with morning coffee... Thank you for your insight @MichaelGeary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.