skip to Main Content

I’m trying to add the arrays inside an array and get a single number from each array. The array looks as follow:

let list = [[1, 2, 3], [4, 5, 6]];

And add the results to the array

This is my code and the result I get is NaN. I already tried editing the code many times getting many results.

var num = 0;
var numberList = [[1, 2, 3], [4,5, 6]];
function add(array, element){
  for(let i in array){
    for(let j in array){
      element = Number.parseInt(array[i][j] + array[i][j]);
    }
  }
  console.log(element);
}
add(numberList, num);

It should add the results to another array. I can push the items to an array, but my first focus is on adding each array. It’s for a project and I can only use the for loop and the only method I can use is the push method

2

Answers


  1. You can use map reduce array functions

    const list = [[1, 2, 3], [4, 5, 6]];
    const result = list.map(e => e.reduce((a, c) => a + c));
    console.log(result);
    

    you can get exactly the same result with nested for loops

    The for…of statement executes a loop that operates on a sequence of values sourced from an iterable object

    const list = [[1, 2, 3], [4, 5, 6]];
    const result = [];
    for(let a of list) {
      result.push(0);
      for(let e of a) {
        result[result.length - 1] += e;
      }
    }
    console.log(result);

    Please see for more details

    Array.prototype.map

    Array.prototype.reduce

    for…of

    Login or Signup to reply.
  2. The issue in your code is that you are overwriting the element variable in each iteration of the inner loop. Instead, you should accumulate the sum of the elements from each sub-array and then add that sum to the result array. You can fix your code like this:

    var numberList = [[1, 2, 3], [4, 5, 6]];
    
    function add(array) {
      var result = []; // Create an empty array to store the sums
    
      for (let i = 0; i < array.length; i++) {
        var sum = 0; // Initialize the sum for each sub-array
    
        for (let j = 0; j < array[i].length; j++) {
          sum += array[i][j]; // Accumulate the sum of elements in the sub-array
        }
    
        result.push(sum); // Add the sum to the result array
      }
    
      return result;
    }
    
    var sums = add(numberList);
    console.log(sums); // [6, 15]
    

    In this code, we initialize an empty result array to store the sums of each sub-array. Then, we iterate through the numberList array, calculate the sum of elements in each sub-array, and push that sum into the result array. Finally, we return the result array containing the sums.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search