I am developing a graph where I have to evaluate the emissions month by month , if that month does not have to put a zero and thus create an array with 12 values (one per month) where I put 0 or the corresponding value. For this I have done this:
const array = []
for (let i = 1; i < 13; i++) {
let existsDatoMes = false;
for (let j = 0; j < mesesGenerado.length; j++) {
if (mesesGenerado[j].month === i) {
existsDatoMes = true
}
}
if (existsDatoMes==true) {
for (let j = 0; j < mesesGenerado.length; j++) {
array.push(mesesGenerado[j].co2)
}
}else {
array.push(0)
}
}
console.log(array)
he mesesGenerado
is the array that returns the emissions, in this case an array of 4, only 4 months have emissions.
The error is that instead of returning an array of 12, it returns an array of 24 doubling the values ,
"Array(24) [ 0, 0, 0, 161.28, 61.44, 453674.8, 1008765.75, 161.28, 61.44, 453674.8, … ]"
how could i fix it? Thank you!!
Maybe something like this will work for you:
I think you can simplify a bit by using array map and find. It would be something like: