- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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], [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 ] ]
Advertisements