I'm trying to sum the values inside an array depending on which levels they are but with no success for the moment.
Datas I'm working with ( named as the variable totalByLevel ) :
What I want :
Having each total per level inside 1 array, for example : ['total of 3 + 4', 'total of 6 + 7', etc...]
What I tried :
I tried to create an empty array and push the values from 3 + 4 into the array, which is working but not as intented.
Only the last values is kept in the array and all others are erased, if you have a fix for it I would really appreciate any help! Thank you in advance.
component.ts
for (const levelKey in this.totalByLevel ) {
if (this.totalByLevel .hasOwnProperty(levelKey)) {
const key = this.labelName[levelKey];
const value = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[0]];
const value2 = this.labelName[Object.keys(this.totalByLevel [levelKey])[0]];
const value3 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[1]];
const value4 = this.totalByLevel [levelKey][Object.keys(this.totalByLevel [levelKey])[2]];
this.output_object[key] = value;
this.output_object2[key] = value2;
const sum = [];
if (value4 !== undefined || null) {
sum.push((+value + +value3 + +value4).toFixed(2));
console.log(sum, 'SUM 3');
this.totalPerCat = sum;
} else if (value4 === undefined || null) {
sum.push((+value + +value3).toFixed(2));
console.log(sum, 'SUM 2');
this.totalPerCat = sum;
} else if (value3 === undefined || null) {
sum.push(value);
console.log(sum, 'SUM 1');
this.totalPerCat = sum;
}
console.log(this.totalPerCat);
/* console.log(value3);
console.log(value4);
console.log(+value + +value3 + +value4, 'SUM');*/
}
}
});


value4 !== undefined || null: I assume you meantvalue4 !== undefined || value4 !== null? The code you wrote would just convert the null to false (due to falsy values), making it useless and only checking for undefined. But you could even take it further:value4 !== undefined || null=>if (value4)value4 === undefined || null=> if (!value4)`. That's the magic of truthy/falsy in JS ;)