-1

I am trying to exclude duplicate numbers from the array. For example: if I filter an array of [1,2,2,3,5,5] the output should be [1,3].

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

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

I was trying not to add duplicate numbers into an array, but instead of [1,3] I am getting [1,2,3,5]

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
JohnPix
  • 1,595
  • 21
  • 44

3 Answers3

1

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]))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

Using Array.reduce, you can get the duplicated count of each item and based on that data, can get the non-duplicated values only as follows.

function unique(arr) {
  const groupBy = arr.reduce((acc, cur) => {
    acc[cur] ? acc[cur] ++ : acc[cur] = 1;
    return acc;
  }, {});
  
  return Object.entries(groupBy)
    .filter(([key, value]) => value === 1)
    .map(([key]) => +key);
}

console.log(unique([1, 2, 2, 3, 5, 5]));
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
1

Count the number of values and returns only those that are equal to 1

function unique(array) {
    var map = new Map();
    array.forEach(a => map.set(a, (map.get(a) || 0) + 1));
    return array.filter(a => map.get(a) === 1);
}

console.log(unique([1, 2, 2, 3, 5, 5]));
54ka
  • 3,501
  • 2
  • 9
  • 24