如何使用 Javascript 中的 reduce() sum/group 多个 "columns/criteria" 的二维数组?
How to sum/group 2d array by multiple "columns/criteria" using reduce() in Javascript?
我一直在研究这个问题,但不知道如何添加列或条件。
这按第一个“列”分组,但如何使其也按最后一列分组?
这是:
let array = [[3, 'name', 'old'],[4, 'lastname','young'],[2, 'name', 'old'],[4, 'lastname','old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; //Add the first element if already exist
else c[v[1]] = v; //Assign the value if does not exist
return c;
}, {}));
console.log(result);
预期结果
result =
[
[5, 'name', 'old'],
[4, 'lastname','young'],
[4, 'lastname','old']
];
谢谢!
这是您要找的吗?
function teste() {
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; else c[v[1]] = v;
if (c[v[2]]) c[v[1]][0] += v[0]; else c[v[2]] = v;
return c;
}, {}));
console.log(result);
}
Execution log
2:03:43 PM Notice Execution started
2:03:43 PM Info [ [ 7, 'name', 'old' ],
[ 7, 'name', 'old' ],
[ 12, 'lastname', 'young' ],
[ 12, 'lastname', 'young' ] ]
2:03:44 PM Notice Execution completed
在你的情况下,作为一个简单的修改,例如,将“B”和“C”列的值作为reduce
对象的键,如下所示?
修改后的脚本:
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
const k = v[1] + v[2];
if (c[k]) c[k][0] += v[0];
else c[k] = v;
return c;
}, {}));
console.log(result);
当此脚本为运行时,得到如下结果
[
[ 5, 'name', 'old' ],
[ 4, 'lastname', 'young' ],
[ 4, 'lastname', 'old' ]
]
我一直在研究这个问题,但不知道如何添加列或条件。 这按第一个“列”分组,但如何使其也按最后一列分组?
这是
let array = [[3, 'name', 'old'],[4, 'lastname','young'],[2, 'name', 'old'],[4, 'lastname','old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; //Add the first element if already exist
else c[v[1]] = v; //Assign the value if does not exist
return c;
}, {}));
console.log(result);
预期结果
result =
[
[5, 'name', 'old'],
[4, 'lastname','young'],
[4, 'lastname','old']
];
谢谢!
这是您要找的吗?
function teste() {
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; else c[v[1]] = v;
if (c[v[2]]) c[v[1]][0] += v[0]; else c[v[2]] = v;
return c;
}, {}));
console.log(result);
}
Execution log
2:03:43 PM Notice Execution started
2:03:43 PM Info [ [ 7, 'name', 'old' ],
[ 7, 'name', 'old' ],
[ 12, 'lastname', 'young' ],
[ 12, 'lastname', 'young' ] ]
2:03:44 PM Notice Execution completed
在你的情况下,作为一个简单的修改,例如,将“B”和“C”列的值作为reduce
对象的键,如下所示?
修改后的脚本:
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
const k = v[1] + v[2];
if (c[k]) c[k][0] += v[0];
else c[k] = v;
return c;
}, {}));
console.log(result);
当此脚本为运行时,得到如下结果
[ [ 5, 'name', 'old' ], [ 4, 'lastname', 'young' ], [ 4, 'lastname', 'old' ] ]