transform a sort into a unique sort

Viewed 53

I'm trying to transform this sort into a unique sort:
const sort = arr => arr.sort((a, b) => a - b);

I tried this:

const uniqSort = arr => {
    const breadcrumbs = {};
    for(let i =0; i<arr.length; i++){ 
        if(breadcrumbs[arr[i]]){ 
            arr.splice(i,1)
        } else { 
            breadcrumbs[arr[i]] = true;
        }
    }
    return arr.sort((a, b) => a - b);
};

for some reason it doesn't work properly, can anyone know why?

when I input uniqSort([4,2,2,3,2,2,2]);
the output is [2,2,3,4] instead of [2,3,4]

1 Answers

You are modifying the same array as you iterating.

const uniqSort = arr => {
  const breadcrumbs = {};
  const newArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (!breadcrumbs[arr[i]]) {
       breadcrumbs[arr[i]] = true;
       newArray.push(arr[i]);
    }
  }
  return newArray.sort((a, b) => a - b);
};

If you are looking for quick solution, how to filter duplicities from array, you can convert it to Set and then back to array.

const uniqSort = arr => {
  return Array.from(new Set(arr)).sort((a, b) => a - b);
};

Related