1

I have made a for each loop to access numbers from a JSON array, the array will be dynamic and forever changing and so I have isolated the numbers inside a variable (the variable is inside the loop). My question is: How do I sum up the numbers that are in the variable.

I tried doing a for loop inside the loop but it didn't work.

it looks kind of like this:

 const arrayhours = Array.from(json_obj); arrayhours.forEach(e=>{ const hours = parseFloat(e.hoursWorked); console.log(hours); //returns for example 1.25 9 5 8 7 as seperate objects. }); 

image of console log

1
  • 1
    let sum = arrayhours.reduce((a, c) => a + +c.hoursWorked, 0); Commented Jan 23, 2020 at 11:50

3 Answers 3

2

You can use Array.reduce() for getting sum of numbers in an array.

const arrayhours = Array.from(json_obj); arrayhours.forEach(e=>{ const hours = parseFloat(e.hoursWorked); console.log(hours); //returns for example 1.25 9 5 8 7 as seperate objects. }); const sum = arrayhours.reduce((acc, val) => acc + parseFloat(val.hoursWorked), 0) 
Sign up to request clarification or add additional context in comments.

2 Comments

That works perfectly, however, I left out one argument, I didn't think it would matter but in this case it does. I have an if argument that narrows down the const "hours" down to hours that are worked inside that period. arrayhours.forEach(e=>{ if(e.UnixTimestamp >= startselect && e.UnixTimestamp <= endselect){ const hours = parseFloat(e.hoursWorked); console.log(hours); //returns for example 1.25 9 5 8 7 as seperate objects. } }) const sum = arrayhours.reduce((acc, val) => acc + parseFloat(val.hoursWorked), 0) console.log(sum); will return sum of entire set in json
Your answer led me to the solution, thanks for the help.
0

Initialize the variable with let hours = 0 before the loop and then use += to add something (instead of =) to assign something.

Finally move the console.log out of the loop:

const arrayhours = Array.from(json_obj); let hours = 0; arrayhours.forEach(e => { const hours += parseFloat(e.hoursWorked); }); console.log(hours); 

Comments

0

const sum = arrayhours.reduce((acc, curr) => acc + parseFloat(curr.hoursWorked, 10), 0)

In comment, AZ_ is using +c.hoursWorked which is a JS trick to cast (if possible) a string into an Int. It is a pretty bad way to to dit, because not really readable. Better use parseInt or parseFloat functions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.