Reputation: 11
I am trying to get a total by using the forEach
in javascript but failing somehow... It just lists the values rather than giving me the total figure
const finances = [
["Jan", 867884],
["Feb", 984655],
["Mar", 322013],
["Apr", -69417],
["May", 310503],
];
let sum2 = 0;
for (let i = 0; i < finances.length - 1; i++) {
let monthDiff = finances[i][1] - finances[i + 1][1];
// console.log(monthDiff)
// console.log(typeof(monthDiff))
const newArray = [monthDiff];
// console.log(newArray)
newArray.forEach((item) => {
sum2 += item;
console.log(sum2); //listing values not giving me a total why?
});
}
Upvotes: 0
Views: 63
Reputation: 601
You have to loop thru each array item and get the 1st index and add it with the current sum.. on first looping, zero is the current sum..
loop no. 1 - currentSum = 0, currentValue[1] = 867884
loop no. 2 - csum = 867884, cval[1] = 984655
loop no. 3 - csum = 867884 + 984655, cval[1] = 322013
...goes on until array end
const finances = [["Jan", 867884], ["Feb", 984655], ["Mar", 322013], ["Apr", -69417], ["May", 310503]];
const total = finances.reduce(
(currentSum, currentValue) => currentValue[1] + currentSum
, 0); // initial sum is zero
console.log(total)
Interms of foreach
const finances = [["Jan", 867884], ["Feb", 984655], ["Mar", 322013], ["Apr", -69417], ["May", 310503]];
let total = 0;
finances.forEach(item => total = item[1] + total);
console.log(total)
Upvotes: 1
Reputation: 130
if using a forEach is not mandatory i would switch to reduce. reduce give you the option to keep track of the previous value as first parameter of the callback. for more info follow the Link.
const array1 = [1, 2, 3, 4];
// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + currentValue,
initialValue
);
console.log(sumWithInitial);
// expected output: 10
Upvotes: 0