所以我的数组如下:array = [ [5, type1, quantity1, price1] , [2, type2, quantity2, price2] , [2, type1, quantity3, price1] ]上述值不是恒定的,它们可以变化。重要的是它们匹配并且加在一起创建 1 个元素。因此,由于array[0]和array[2]具有相同的类型和价格 ( array[n][1] and array[n][3]),因此生成的数组应如下所示:[ [7, type1, quantity1+quantity3, price1], [2, type2, quantity2, price2]]该数组的长度为 N。我正在尝试找到执行此操作的最佳算法,但找不到。
1 回答

MMMHUHU
TA贡献1834条经验 获得超8个赞
您可以使用组合钥匙并增加价值和数量。
const
array = [[5, 'type1', 10, 'price1'], [2, 'type2', 11, 'price2'], [2, 'type1', 12, 'price1']],
grouped = Object.values(array.reduce((r, [value, type, quantity, price]) => {
const key = [type, price].join('|');
if (r[key]) {
r[key][0] += value;
r[key][2] += quantity;
} else r[key] = [value, type, quantity, price];
return r;
}, {}));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报
0/150
提交
取消