Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading