Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Grouping and sorting 2-D array in JavaScript
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], [3], [4], [5] ];
How It Works
The solution involves two main steps:
- Grouping: Flatten the 2D array and group identical numbers together
- Sorting: Sort the groups by their numeric value in ascending order
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
[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]
Alternative Approach Using Modern Methods
Here's a more concise solution using flat() and reduce():
const arr = [
[1, 3, 2],
[5, 2, 1, 4],
[2, 1]
];
const groupAndSortModern = arr => {
const flattened = arr.flat();
const grouped = flattened.reduce((acc, num) => {
if (!acc[num]) acc[num] = [];
acc[num].push(num);
return acc;
}, {});
return Object.keys(grouped)
.sort((a, b) => a - b)
.map(key => grouped[key]);
};
console.log(groupAndSortModern(arr));
Output
[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]
Conclusion
Both approaches effectively group and sort 2D arrays. The first uses traditional iteration, while the second leverages modern array methods like flat() and reduce() for cleaner code.
Advertisements
