在JavaScript中对二维数组进行分组和排序
假设我们有一个二维数字数组,如下所示:
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 ] ]
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短