I’m trying to find the sum total of the arrays nested inside of the parent array. and push the sums into their own array. only using the for loop.
I could be way off here, I can’t seem to get past how to find the sum of the second array i know how to find the sum of just one, but when another is thrown into the mix it gets a little dicy and starts flagging errors. any suggestions or thought exercises are more than welcome!
let array = [[1,3,3,5,6],[1,3,6,5,6]];
let sum = 0;
let newArray = []
for(let i = 0; i < array.length; i++){
sum+=array[i]
newArray.push(sum)
}
console.log (newArray)
// expected output should be 'newArray =[18,21]'
3
Answers
There are two things incorrect with your code.
The way you are instantiating the array ‘array’ is incorrect. You want an array of arrays. Therefore you must use brackets to indicate the top level array, the same way you used brackets to indicate that the two inner arrays are arrays.
let array = [[1,3,3,5,6],[1,3,6,5,6]];
should do the trick.You have a 2-dimensional array by definitions (an array of arrays), so you can’t have a 1-dimensional for loop. You must iterate over the two dimensions by nesting another for loop within your current one. The outermost for loop will iterate over each array, and the inner loop will iterate over each element at the given array. See: Iterate through 2 dimensional array
You’re looping over the amount of outer arrays, not the inner ones. So
sum+=
does not calculate the sum.USing this:
How to find the sum of an array of numbers, you can do it like so
But then you could use another map to make it a lot more readable:
If you want to use a for-loop, you can do this, but it is not advised.
Note: This is a very naive; non-idiomatic approach.
Alternatively, you can initialize the array with zeros. This saves the hassle of setting up an intermediary sum counter.
Functional approach
In a purely functional approach to this problem, break it down into smaller pieces.
Here it is again, in one-shot: