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

Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript


We are required to write a JavaScript function that takes in an array of numbers as one and the only input. The input array will probably contain some duplicate entries.

Our function should sort the array and group all the identical (duplicate) numbers into their separate subarray.

For example −

If the input array is −

const arr = [5, 7, 5, 7, 8, 9, 1, 1];

Then the output should be −

const output = [
   [1, 1],
   [5, 5],
   [7, 7],
   [8],
   [9]
];

Example

The code for this will be −

const arr = [5, 7, 5, 7, 8, 9, 1, 1];
const sortAndGroup = (arr = []) => {
   let result = [];
   let groupArray;
   arr.sort((a, b) => a - b);
   for (let i = 0; i < arr.length; i++) {
      if (arr[i − 1] !== arr[i]) {
         groupArray = [];
         result.push(groupArray);
      };
      groupArray.push(arr[i]);
   };
   return result;
};
console.log(sortAndGroup(arr));

Output

And the output in the console will be −

[ [ 1, 1 ], [ 5, 5 ], [ 7, 7 ], [ 8 ], [ 9 ] ]