基于其第一个值拆分数组 - JavaScript
假设我们有一个这样的数字数组数组:-
const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];
每个子数组都严格包含两个元素。我们需要编写一个函数,该函数构造一个新数组,其中所有具有相似第一个值的子数组的第二个元素被组合在一起。
因此,对于上面的数组,输出应如下所示:-
const output = [ [45, 34, 49], [34, 67], [78, 65] ];
我们可以利用 Array.prototype.reduce() 方法来借助 Map() 构造所需的数组。
示例
以下是代码:-
const arr = [[1, 45], [1, 34], [1, 49], [2, 34], [4, 78], [2, 67], [4, 65]];
const constructSimilarArray = (arr = []) => {
const creds = arr.reduce((acc, val) => {
const { map, res } = acc;
if(!map.has(val[0])){
map.set(val[0], res.push([val[1]]) - 1);
}else{
res[map.get(val[0])].push(val[1]);
};
return { map, res };
}, {
map: new Map(),
res: []
});
return creds.res;
};
console.log(constructSimilarArray(arr));输出
这会在控制台中生成以下输出:-
[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP