javascript - 在javascript中合并数组本身
问题描述
我的数组如下所示:
{"type":"send","name":"kebab","quantity":"1"},
{"type":"send","name":"potato","quantity":"25000"},
{"type":"receive","name":"money","quantity":"1"},
{"type":"receive","name":"soul","quantity":"12"},
{"type":"receive","name":"paper","quantity":"8"},
{"type":"send","name":"kebab","quantity":"1"},
{"type":"send","name":"potato","quantity":"25000"},
{"type":"receive","name":"money","quantity":"1"},
{"type":"receive","name":"soul","quantity":"12"},
{"type":"receive","name":"paper","quantity":"8"}
我希望它合并到将添加或减去值的新数组中,如下所示:
{"type":"send","name":"kebab","quantity":"2"},
{"type":"send","name":"potato","quantity":"50000"},
{"type":"receive","name":"money","quantity":"2"},
{"type":"receive","name":"soul","quantity":"24"},
{"type":"receive","name":"paper","quantity":"16"}
我不知道该怎么做
更新:类型和名称应该保持不变,只有数量会改变
解决方案
您可以将项目减少到一个新数组并将数量相加。
const items = [{"type":"send","name":"kebab","quantity":"1"},
{"type":"send","name":"potato","quantity":"25000"},
{"type":"receive","name":"money","quantity":"1"},
{"type":"receive","name":"soul","quantity":"12"},
{"type":"receive","name":"paper","quantity":"8"},
{"type":"send","name":"kebab","quantity":"1"},
{"type":"send","name":"potato","quantity":"25000"},
{"type":"receive","name":"money","quantity":"1"},
{"type":"receive","name":"soul","quantity":"12"},
{"type":"receive","name":"paper","quantity":"8"}]
let result = items.reduce((arr, item) => {
// Find the item in the new array by name
let found = arr.find(i => i.name == item.name && i.type == item.type)
// If the item doesn't exist add it to the array
if(!found) return arr.concat(item)
// If the item does exist add the two quantities together
// This will modify the value in place, so we don't need to re-add it
found.quantity = parseFloat(item.quantity) + parseFloat(found.quantity)
// Return the new state of the array
return arr;
}, [])
console.log(result)