I am trying to create and new array from and existing one.
The new one needs to include zero values for missing data.
Additionally the categories are corresponding to months and need to be replaced.
Original Array
[
{
"name": "2023",
"data": 10,
"categories": 7
},
{
"name": "2023",
"data": 1688,
"categories": 8
},
{
"name": "2023",
"data": 373,
"categories": 9
},
{
"name": "2022",
"data": 211,
"categories": 9
}
]
New Array
[
{
name: "2022",
data: [44, 55, 41, 37, 22, 43, 21, 33, 52, 13, 43, 32],
categories: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
},
{
name: "2023",
data: [424, 43, 66, 11, 22, 21, 32, 43, 55, 6, 86, 42],
categories: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
}
]
The issue is that i need create this new array with all 12 months for each available year and if the month is missing it should default to 0.
The new array would basically look like this with the original data provided above.
[
{
name: "2022",
data: [0,0,0,0,0,0,0,0,211,0,0,0,],
categories: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
},
{
name: "2023",
data: [0,0,0,0,0,0,10,1688,373,0,0,0,],
categories: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
}
]
I’m not sure if that’s even possible, but any help is greatly appreciated.
I’ve tried all sorts of techniques, but get stuck on auto filling data for missing months.
3
Answers
You can use
Array#reduce
with an object to store the data for each year.Simple reduce will do it
Here is a Codepen sample, that might do the trick.
https://codepen.io/bellmorecode/pen/JjwEoyw
Here is the code:
The output looks like this:
[{"name":"2023","data":[10,1688,373],"categories":[7,8,9]},{"name":"2022","data":[211],"categories":[9]}]