exclude duplicates from the array duplicate

The easiest tweak would be to check that both the next element and the previous element don’t equal the current element:

function unique(arr) {
  let sortArr = arr.sort()
  let res = []
  for (let i = 0; i < arr.length; i++) {
    if (sortArr[i] != sortArr[i + 1] && sortArr[i] !== sortArr[i - 1]) {
      res.push(sortArr[i])
    }
  }
  return res
}

console.log(unique([1, 2, 2, 3, 5, 5]))

But .sort has a computational complexity of O(n log n). This can be done in O(n) time by counting up the number of results in an object instead:

function unique(arr) {
  const ones = new Set();
  const dupes = new Set();
  for (const item of arr) {
    if (dupes.has(item)) continue;
    if (ones.has(item)) {
      dupes.add(item);
      ones.delete(item);
    } else ones.add(item);
  }
  return [...ones];
}

console.log(unique([1, 2, 2, 3, 5, 5]))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top