减少-分成多个批次

时间:2018-07-10 23:59:54

标签: javascript node.js

我试图弄清楚如何将Batch分成几组。例如,res应该返回两个批次的FG

var data = {
    Items: [{
        ItemId: "222",
        Sum: 2,
        Batch: "F"
    }, {
        ItemId: "222",
        Sum: 2,
        Batch: "F"
    }, {
        ItemId: "333",
        Sum: 3,
        Batch: "G"
    }, {
        ItemId: "333",
        Sum: 5,
        Batch: "F"
    }, ]
};

var res = data.Items.reduce((acc,obj)=>{
    var existObj = acc.find(item=>item.Id === obj.ItemId);

    if (existObj) {
        existObj.Sum += obj.Sum;

        return acc;
    }

    acc.push({
        Id: obj.ItemId,
        Sum: obj.Sum
    });

    return acc;
}
, []);

当前它输出如下:

[
  {
    "Id": "222",
    "Sum": 4
  },
  {
    "Id": "333",
    "Sum": 8
  }
]

以上逻辑,如果对象中存在ItemId,它将添加Sum。它结合了ItemId来删除重复项。

应将其拆分为多个批次,并基于Batch考虑Sum。例如,预期输出如下:

{
  "Batch": [
    {
      "BatchName": "F",
      "Lines": [
        {
          "Id": "222",
          "Sum": 4
        },
        {
          "Id": "333",
          "Sum": 5
        }
      ]
    },
    {
      "BatchName": "G",
      "Lines": [
        {
          "Id": "333",
          "Sum": 3
        }
      ]
    }
  ]
}

注意:结构不必相同

1 个答案:

答案 0 :(得分:2)

遵循应该可以为您提供所需的东西

public class Kata{
    public static double find_average(int[] array){

    int avr = 0;

  for(int a = 0; a < array.length; a++) {
     avr = avr + array[a];
  }
      System.out.println("hello");
      double average = avr / array.length;
      return average;
  }
}
var tmp = data.Items.reduce((a,{ItemId, Sum, Batch})=>{
   a[Batch] = a[Batch] || {}
   a[Batch][ItemId] = a[Batch][ItemId] || {ItemId, Sum:0}
   a[Batch][ItemId].Sum += Sum
   return a;

},{});

var res = Object.keys(tmp)
      .reduce((a,k)=> a.concat({BatchName: k, Lines: Object.values(tmp[k])}),[])
      
console.log(res)