Grouping and sorting 2-D array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have a two-dimensional array of numbers like this −

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

We are required to write a JavaScript function that groups all the identical numbers into their own separate subarray, and then the function should sort the group array to place the subarrays into increasing order.

Therefore, finally the new array should look like −

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

Example

The code for this will be −

const arr = [
   [1, 3, 2],
   [5, 2, 1, 4],
   [2, 1]
];
const groupAndSort = arr => {
   const res = [];
   const map = Object.create(null);
   Array.prototype.forEach.call(arr, item => {
      item.forEach(el => {
         if (!(el in map)) {
            map[el] = [];
            res.push(map[el]);
         };
         map[el].push(el);
      });
   });
   res.sort((a, b) => {
      return a[0] - b[0];
   });
   return res;
};
console.log(groupAndSort(arr));

Output

The output in the console −

[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]
raja
Published on 12-Oct-2020 11:40:28
Advertisements