在 JavaScript 中对二维数组进行分组和排序
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 11:56:17
假设我们有一个像这样的二维数字数组 −
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 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

