Create object array base on different value

I have these data

[
    {
        "Month": 2,
        "SubjectID": 25,
        "TitleName": "TEST32",
        "Average": 85
    },
    {
        "Month": 4,
        "SubjectID": 1,
        "TitleName": "TEST",
        "Average": 63
    },
    {
        "Month": 4,
        "SubjectID": 25,
        "TitleName": "TEST32",
        "Average": 88
    }
]

i want to transform this into array object that will base on subject id and the month.
I don’t know if this is possible.

but i want to create a year array where the average will display in array index of created array base on month number.

Output like this

    {
        name: 'TEST',
        data: [0, 0, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0]
    },
    {
        name: 'TEST32',
        data: [0, 85, 0, 88, 0, 0, 0, 0, 0, 0, 0, 0]
    }

>Solution :

You could use Array#reduce with an object to store the 12 averages for each name.

let arr=[{Month:2,SubjectID:25,TitleName:"TEST32",Average:85},{Month:4,SubjectID:1,TitleName:"TEST",Average:63},{Month:4,SubjectID:25,TitleName:"TEST32",Average:88}];
let res = Object.values(arr.reduce((acc, {Month, SubjectID, TitleName : name, Average}) => {
  (acc[name] ??= {name, data: Array(12).fill(0)}).data[Month - 1] = Average;
  return acc;
}, {}));
console.log(res);

Leave a Reply