JavaScript中移除数组连续重复对象并合并数量的实现
合并数组中连续同类型对象的数量
给定一个包含产品对象的数组,其中存在连续重复的产品(依据type字段判断)。需要移除连续重复的产品对象,将重复对象的qty值累加到最后一个重复对象中。
原数组
let books = [ { id: "1", type: "D", price: 25, qty: 27},// * { id: "2", type: "D", price: 22, qty: 75},// * { id: "3", type: "D", price: 21, qty: 19},// * { id: "4", type: "D", price: 19, qty: 62}, { id: "5", type: "U", price: 23, qty: 19}, { id: "6", type: "D", price: 20, qty: 22}, { id: "7", type: "U", price: 25, qty: 14},// * { id: "8", type: "U", price: 29, qty: 14} ]
预期结果
[ { id: "4", type: "D", price: 19, qty: 121}, { id: "5", type: "U", price: 23, qty: 19}, { id: "6", type: "D", price: 20, qty: 22}, { id: "8", type: "U", price: 29, qty: 28} ]
解决方案
可以用数组的reduce方法高效处理这个需求,遍历数组时维护一个结果集合,判断当前元素与结果最后一个元素的类型是否一致,一致则累加数量并保留最后一个元素的属性,否则直接添加新元素。
const mergedBooks = books.reduce((result, current) => { const last = result[result.length - 1]; if (last && last.type === current.type) { // 累加数量,并用当前元素的属性覆盖最后一个元素(保留累加后的qty) last.qty += current.qty; result[result.length - 1] = { ...current, qty: last.qty }; } else { result.push(current); } return result; }, []);
这段代码的逻辑:
- 初始化空数组
result作为最终结果容器 - 遍历每个产品对象
current,取出结果数组的最后一个元素last - 如果
last存在且和current的type相同,就把current的qty加到last的qty上,然后用current的其他属性(id、price)替换last,同时保留累加后的qty - 如果类型不同,直接把
current加入结果数组
运行后就能得到符合预期的合并结果。
内容的提问来源于stack exchange,提问作者Ben Davidsson
相关产品推荐
相关产品推荐

