How to check whether the items are unique in an array using JavaScript

Viewed 69

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 Answers

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

Related