javascript - 连接具有相似值的二维数组中的元素
问题描述
所以我的数组如下:
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。我正在尝试找到执行此操作的最佳算法,但找不到。
提前致谢。
解决方案
您可以使用组合键并添加价值和数量。
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; }
推荐阅读
- ruby-on-rails - 如何向 form_with 添加隐藏字段?
- r - R值;将字符串平均分成两部分
- vis.js - 如何从集群中获取所有边缘 ID
- javascript - 在相同位置的html DOM元素中替换后转换字符串
- r - 在R中的森林图标题中将两列合并为一行
- firebase - 将集合从云存储导入到 Firestore
- javafx - 如何检测我的 javaFX 应用程序是否已关闭?
- css - 是否有 JavaFX CSS 属性将节点的背景设置为边框的大小/形状?
- r - 在 Windows 上具有抗锯齿和 wmf 格式的 R ggplots
- apache-kafka - 卡夫卡不会启动