分组和排序 2D 数组
假设我们有一个这样的数字二维数组 −
const arr = [ [1, 3, 2], [5, 2, 1, 4], [2, 1] ];
我们要求编写一个 JavaScript 函数,将所有相同的数字分组到其自己的独立子数组中,然后函数应该对组数组进行排序,按升序排列子数组。
因此,最终新数组应如下所示 −
const output = [ [1, 1, 1], [2, 2, 2], [4], [3], [5] ];
示例
代码如下 −
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));输出
控制台中的输出 −
[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP