Search code examples
javascriptangulartypescriptlogiclodash

How to add sum of same objects using lodash


I am new to development.

I want to group the same objects inside array of json objects. E.g. here is my JSON array:

var data = [
    {
        zone: "Bottom",
        group: "Bottom girders",
        original: 7,
        gauge: 3,
        dPercent: 0,
        permissible: 10,
    },
    {
        zone: "Bottom",
        group: "Bottom girders",
        original: 9,
        gauge: 7,
        dPercent: 0,
        permissible: 10,
    },
    {
        zone: "Bottom",
        group: "risers",
        original: 7,
        gauge: 3,
        dPercent: 0,
        permissible: 10,
    },
    {
        zone: "Neutral axis",
        group: "Transverse PSM",
        original: 17,
        gauge: 28,
        dPercent: 0,
        permissible: 15,
    },
    {
        zone: "Neutral axis",
        group: "Transverse PSM",
        original: 17,
        gauge: 12,
        dPercent: 0,
        permissible: 15,
    },
];

The final output I expect is:

[
      {
        "zone": "Neutral Axis",
        "groups": [
           { "zone":"Bottom", "group":"Bottom girders","original": 34, "gauge": 40, "dPercent": 5.3, "permissible": 10 }
        ]
      },
      {
        "zone": "Bottom",
        "groups": [
           { "zone":"Bottom", "group":"Bottom girders", "original": 16, "gauge": 10, "dPercent": 5.3, "permissible": 10 },
           { "zone":"Bottom", "group":"risers", "original": 7, "gauge": 3, "dPercent": 5.3, "permissible": 10 }
        ]
      }
    ]

Logic: I want to club data zone wise first then each zone having different group and based on group i want to add original and gauge values final output as shown

Here is my code link i have tried https://angular-ivy-zm5kqo.stackblitz.io

Thank you so much in Advance !


Solution

  • From your output example I suppose that you want group your entities by their zone property, and get result as an array.

    The code that do it:

    var data = [/*your data here*/];
    
    var groupedData = _.groupBy(data, 'zone');
    var result = _.map(groupedData, (value, key) => {
      return {
        "zone": key,
        "groups": value
      }
    });
    

    It can be chained, if you like that way:

    var result = _.chain(data)
      .groupBy('zone')
      .map((value, key) => {
        return {
          "zone": key,
          "groups": value
        }
      }).value();
    

    _.groupBy transforms your data array into object like this:

    {
       "Bottom":[
          /* All entities where zone is "Bottom" */
       ],
       "Neutral axis":[
          /* All entities where zone is "Neutral axis" */
       ]
    }
    

    Then we transform this object into array of your desired objects using _.map.

    Resources:

    https://lodash.com/docs/4.17.15#groupBy

    https://lodash.com/docs/4.17.15#map

    https://lodash.com/docs/4.17.15#chain