Interview Questions

  • View all tutorials
  • blank
  • Sum of several arrays
    The questions is as follows:
    You will be given an array of several arrays that each contain integers and your goal is to write a function that will sum up all the numbers in all the arrays. For example, if the input is [[3, 2], [1], [4, 12]] then your program should output 22 because 3 + 2 + 1 + 4 + 12 = 22.

    Solution

    We will solve this challenge by looping through the entire array, and then looping through each inner array adding up all the numbers.

    Code

    function sum_array(arr) {
      
      // store our final answer
      var sum = 0;
      
      // loop through entire array
      for (var i = 0; i < arr.length; i++) {
        
        // loop through each inner array
        for (var j = 0; j < arr[i].length; j++) {
          
          // add this number to the current final sum
          sum += arr[i][j];
          
        }
        
      }
      
      return sum;
      
    }
    
    sum_array([[3, 2], [1], [4, 12]]);
    
    def sum_array(arr):
      
      # store our final answer
      final_sum = 0
      
      # loop through entire array
      for i in range(0, len(arr)):
        
        # loop through each inner array
        for j in range(0, len(arr[i])):
    
          # add this number to the current final sum
          final_sum += arr[i][j]
          
      return final_sum
        
    print sum_array([[3, 2], [1], [4, 12]])
    
    Run Code
    Run Code
    mrdaniel published this on 12/14/15 | javascript, bootcamp, array, recursion, Fullstack Academy
    Comments
  • +
  • 5
  • -
  • With functional programming:
    function sumArray(arr) {
      return arr.reduce((t, e) => t.concat(e)).reduce((t, e) => t + e)
    }
  • +
  • 2
  • -
  • 
    function sumNestedArrays(array) {
    	
    	var flattenedArray = [];
    	
    	array.forEach(function(element) {
    		if (Array.isArray(element))
    			flattenedArray.push(sumNestedArrays(element));
    		else flattenedArray.push(element);
    	});
    	
    	return flattenedArray.reduce(function(a,b) {
    		return a+b;
    	});
    }
    
  • +
  • 1
  • -
  • function addArray(arr){
    
    var count = 0;
    
    for(var i=0; i<arr.length; i++){
    	count += arr[i].reduce(function(c, p){return c + p});
    }
    return count;
    };
    addArray([[3, 2], [1], [4, 12]]);
    
  • +
  • 1
  • -
  • function sum_array(arr) {
      return arr.reduce(function (a, b) {
        return a.concat(b);
      }).
      reduce(function (a, b) {
        return a + b;
      });
    }
    
  • +
  • 0
  • -
  • //@ shaunw throw's an exception function multi_array_sum (arr){ var result = arr.reduce(function (a, b) { return a.concat(b);},[]) return result.reduce(function(a,b) { return a+b;} ); } // if this can be pared further have at it everyone
  • +
  • 0
  • -
  • This solution only works with 1 "nested layer" of arrays. In case you're asked to find a solution for n "nested layers"(like I was recently..) I suggest you use recursion and Python's "type" method(I know how to do this in Ruby as well, but not sure about JS) Something like this:
    def my_function(arr):
        my_sum = 0
        for elm in arr:
            if type(elm) == int:
                my_sum += elm
            elif type(elm) == list:
                temp = my_function(elm)
                my_sum += temp
        return my_sum
                
    my_list = [1,[2,[3,4]],5]
    print my_function(my_list)
    
  • +
  • 0
  • -
  • my_list = [[3, 2], [1], [4, 12]]
    my_sum = 0
    
    for sub_list in my_list:
        for item in sub_list:
            my_sum = my_sum + item
    
    print my_sum
    
  • +
  • 0
  • -
  • function sumItUp(arr) {
        var result = 0;
    	arr.forEach(function(ele, i) {
        if(Array.isArray(ele)){
            ele.forEach(function(el, i) {
                result+=el;
            });
        }else {
            result+= ele;
        }
    });
    return result;
    }
    Log in to submit a comment.