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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ] ]
raja
Updated on 23-Nov-2020 07:20:15

Advertisements