Computer >> Computer tutorials >  >> Programming >> Javascript

Unique sort (removing duplicates and sorting an array) in JavaScript


The simultaneous technique of removing duplicates and sorting an array is often termed as a unique sort technique.

For example, if the input array is −

const arr = [1, 1, 1, 3, 2, 2, 8, 3, 4];

Then the output should be −

const output = [1, 2, 3, 4, 8];

Example

The code for this will be −

const arr = [1, 1, 1, 3, 2, 2, 8, 3, 4];
const uniqSort = (arr = []) => {
   const map = {};
   const res = [];
   for (let i = 0; i < arr.length; i++) {
      if (!map[arr[i]]) {
         map[arr[i]] = true;
         res.push(arr[i]);
      };
   };
   return res.sort((a, b) => a − b);
};
console.log(uniqSort(arr));

Output

And the output in the console will be −

[ 1, 2, 3, 4, 8 ]