How to group and sum JSON data array

๐Ÿ‘:1

In that case, how about the following sample script?

Sample script:

const timeStamp = ['2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-03', '2022-12-03', '2022-12-03'];
const stroke = ['1', '0', '0', '0', '1', '0', '0'];
const tbi = ['0', '1', '1', '1', '0', '0', '1'];
const sci = ['0', '0', '0', '0', '0', '1', '0'];

const res = [...timeStamp.reduce((m, e, i) => {
  const o = m.get(e);
  const v1 = Number(stroke[i]) + (o?.dxGroup.stroke ? Number(o.dxGroup.stroke) : 0);
  const v2 = Number(tbi[i]) + (o?.dxGroup.tbi ? Number(o.dxGroup.tbi) : 0);
  const v3 = Number(sci[i]) + (o?.dxGroup.sci ? Number(o.dxGroup.sci) : 0);
  return m.set(e, { timeStamp: e, dxGroup: { stroke: v1.toString(), tbi: v2.toString(), sci: v3.toString() } });
}, new Map()).values()];
console.log(res);

Testing:

When this script is run, the following result is obtained.

[
  { "timeStamp": "2022-12-01", "dxGroup": { "stroke": "1", "tbi": "1", "sci": "0" } },
  { "timeStamp": "2022-12-02", "dxGroup": { "stroke": "0", "tbi": "2", "sci": "0" } },
  { "timeStamp": "2022-12-03", "dxGroup": { "stroke": "1", "tbi": "1", "sci": "1" } }
]

Reference:

๐Ÿ‘:1

You can try this one

    const timeStamp = [  '2022-12-01', '2022-12-01', '2022-12-02', '2022-12-02', '2022-12-03', '2022-12-03', '2022-12-03'  ]

    const stroke = [ '1', '0', '0', '0', '1', '0', '0' ]
    const tbi =    [ '0', '1', '1', '1', '0', '0', '1' ]
    const sci =    [ '0', '0', '0', '0', '0', '1', '0' ]



    //Format Data

    let result =[];

    timeStamp?.forEach((item, index) => {
      let resultObj = {timeStamp:item}
      let dxGroup = {stroke: stroke[index], tbi: tbi[index], sci:sci[index]}
      resultObj = {...resultObj, dxGroup}

      result.push(resultObj)
    })

    console.log(result)

Leave a comment