I have an array of objects of this structure

- day
- dimension
- sub-dimension
  ...
- sub-sub-dimension
- measure1, measure2,...

and want to convert into this structure to feed into a dashboard template, with the “diff” is DoD difference.

- day
- dimension
- sub-dimension
  ...
- sub-sub-dimension
- measure1: [value,#diff,%diff]
- measure2: [value,#diff,%diff]
  ...

My best logic so far is

  • Loop through the data and group by every value combinations of dimensionList.
  • Popular the an array for each measure of each combination measureList with all days.
  • Calculate rolling difference for each measure.
  • Update back to the original data.

My best attemp failed at the first step at generating the array for each combinations and my logic isn’t neat as well. Hope someone could help, it’s okay to use packages.

    const dimensionList = ["city","category"];
    const measureList = ["order","buyer","gmv"];
    const newData = [];
    measureList.forEach(measure => {
      newData.push(
        {
          measure: measure,
          values: _.chain(data)
                   .groupBy(data,item => dimensionList.map(dim => item[dim]).join('-'))
                   .mapValues(group => _.map(group, measure))
                   .value()
        }
      )
    });

Example data and the expected results

[
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "X",
        "order": 100,
        "buyer": 150,
        "gmv": 1000
    },
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "Y",
        "order": 110,
        "buyer": 160,
        "gmv": 1200
    },
    {
        "day": "2024-01-02",
        "city": "A",
        "category": "X",
        "order": 120,
        "buyer": 170,
        "gmv": 1400
    },
    ...
]
[
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "X",
        "order": [100,null,null]
        "buyer": [50,null,null]
        "gmv": [1000,null,null]
    },
    {
        "day": "2024-01-01",
        "city": "A",
        "category": "Y",
        "order": [110,null,null]
        "buyer": [160,null,null]
        "gmv": [1200,null,null]
    },
    {
        "day": "2024-01-02",
        "city": "A",
        "category": "X",
        "order": [125,25,0.25]
        "buyer": [60,10,0.2]
        "gmv": [1400,400,0.4]
    },
    ...
]

New contributor

Lukest_Dang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.