data:
const data = [
{time: "2020-10-13", value: 3},
{time: "2020-11-13", value: 30},
{time: "2021-01-13", value: 12},
{time: "2021-02-13", value: 1},
{time: "2021-03-13", value: 23},
{time: "2021-04-13", value: 10}, ...
]
Im formating this data to this format: [number, number, number][] –> [month, year, value]
For the example data it would be:
[[11, 2020, 3], [10, 2020, 30], [1, 2021, 12], [2, 2021, 1], ...]
How can I add value 0 and month, when the month is missing? So in example, there is 10 months missing in 2020 and 9 months missing in 2021. I would like to add it so it looks like this:
[[1, 2020, 0], [2, 2020, 0],[3, 2020, 0], [4 2020, 0],[5, 2020, 30, [6, 2020, 0],[7, 2020, 0],[8, 2020, 0],[9, 2020, 0], [10, 2020, 30],[11, 2020, 3], [10, 2020, 30], [1, 2021, 12], [2, 2021, 1], ...]
What would be the best way to do it?
Thanks!!
EDIT:
some code I tried:
const months =[1,2,3,4,5,6,7,8,9,10,11,12];
const res = data.flatMap(({time,value}) => {
const [y,m,d] = time.split("-").map(Number);
const res = months.map((month, i) => {
if (m === month) {
return [m, y, value]
} else {
return [month, y, 0]
}
})
return res;
})
const changeData = (data) => {
let res = {};
data.forEach((item) => {
const {time, value} = item;
const [y,m,d] = time.split("-").map(Number);
res[y] !== undefined ? res[y].push({m, value})
: res[y] = [{m, value}];
})
return res;
}
const newData = changeData(data);
console.log(newData)
const months =[1,2,3,4,5,6,7,8,9,10,11,12];
const formatData = () => {
let result = [];
for (const [key, value] of Object.entries(newData)) {
value.slice(0, 12).map((val, i) => {
const y = key;
const {m, value} = val;
const res = months.map((month, i) => {
if (m === month) {
result.push([m, y, value]);
} else {
result.push([month, y, 0]);
}
})
})
}
return result;
}
2
Answers
You should be looping over the time range, not the entries in the
newData
dictionary. For each month, check if it appears innewData
. Use that value if it exists, otherwise default to 0.This can be done using reduce(). Create all months for years first, then add
value
to them: