Search code examples
javascriptfor-loop

Finding the Sum of multiple arrays nested in one array


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]'


Solution

  • 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.

    let array = [[1, 3, 3, 5, 6], [1, 3, 6, 5, 6]];
    
    let newArray = new Array(array.length);
    for (let r = 0; r < array.length; r++) {
      let sum = 0;
      for (let c = 0; c < array[r].length; c++) {
        sum += array[r][c];
      }
      newArray[r] = sum;
    }
    
    console.log(newArray); // [18, 21]

    Alternatively, you can initialize the array with zeros. This saves the hassle of setting up an intermediary sum counter.

    let array = [[1, 3, 3, 5, 6], [1, 3, 6, 5, 6]];
    
    let newArray = new Array(array.length).fill(0);
    for (let r = 0; r < array.length; r++) {
      for (let c = 0; c < array[r].length; c++) {
        newArray[r] += array[r][c];
      }
    }
    
    console.log(newArray); // [18, 21]


    Functional approach

    In a purely functional approach to this problem, break it down into smaller pieces.

    1. How do I add two numbers? (simple add reducer function)
    2. How can I add multiple numbers? (reduce the array with the reducer, initialized at 0)
    3. How can I do this for a matrix? (map over the array and call the sum reducer)

    const add = (a, b) => a + b
    const sum = (n) => n.reduce(add, 0)
    
    let data = [[1, 3, 3, 5, 6], [1, 3, 6, 5, 6]]
    let sums = data.map(sum)
    
    console.log(sums) // [18, 21]

    Here it is again, in one-shot:

    let data = [[1, 3, 3, 5, 6], [1, 3, 6, 5, 6]]
    let sums = data.map((n) => n.reduce((a, b) => a + b, 0))
    
    console.log(sums) // [18, 21]