Home > Mobile >  get sum total by using foreach
get sum total by using foreach

Time:11-25

I am trying to get a total by using the foreach in javascript but failing somehow...it just lists the values rather than give me 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?
  });
}

CodePudding user response:

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

CodePudding user response:

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

let total = 0;
finances.forEach(item => total = item[1]   total);
console.log(total)
  • Related