在JavaScript中合并数组本身

时间:2018-06-29 15:43:49

标签: javascript arrays

我的数组如下:

{"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"}

我不知道该怎么做

更新:类型和名称应保持不变,只更改数量

2 个答案:

答案 0 :(得分:3)

您可以将reduce个项目放到一个新的数组中并添加数量。

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)

答案 1 :(得分:0)

您可以使用reduce将数组分组为一个对象。使用Object.values将对象转换为数组。

var arr = [{"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"}];

var result = Object.values(arr.reduce((c, v) => {
  c[v.name] = c[v.name] || {type: "",name: v.name,quantity: 0};
  c[v.name].quantity += +v.quantity;   //Update the quantity
  c[v.name].type = v.type;             //Update the type
  return c;
}, {}));

console.log(result);