Function accessing Array of Array

Hello, I am new to the forum and early on in my JavaScript learning. I have a problem that has me stumped which is using a function to access an array within an array and then summing the values at the specific index.

Here I am using a for loop to access elements of the array and then adding them and I get the expected result. However I believe this approach would be considered “hard coding” for the array. When I try to build a function, to access the values, it does not work. Any assistance to point me in the right direction would be greatly helpful.

Here is my for loop of the specific array:

const numbers = [
  [-4, 2, 1],
  [0, -1, 2],
  [2, 2, 3]
];
  for (var i = 0; i < numbers.length; i++) {
       for (var j = 0; j < numbers[i].length; j++) {
    var sum = numbers[0][2] + numbers[1][2] + numbers[2][2];
    var sum2 = numbers[0][0] + numbers[1][0] + numbers[2][0];
      }
 }
console.log(sum); //--> returns 6 (i.e. 1 + 2 + 3)
console.log(sum2);//--> returns -2 (i.e. -4 + 0 + 2)

However when I try to perform this same action with a function it is not returning the expected results:

const numbers = [
  [-4, 2, 1],
  [0, -1, 2],
  [2, 2, 3]
];
function addNestedNumbers(arr, identifier) {
  for (var i = 0; i < arr.length; i++) {
     for (var j = 0; j < arr[i].length; j++) {
     
    }
   return arr[identifier];
  }
  //sumTotal = arr[i] + arr[j];
//return sumTotal;
}
// Examples:
console.log(addNestedNumbers(numbers, 2));  //--> returns 6 (i.e. 1 + 2 + 3)
//console.log(addNestedNumbers(numbers, 0));  //--> returns -2 (i.e. -4 + 0 + 2)

you don’t need the second loop, you can do it with only one loop, because the inner array has a fixed index to access.
access each array with the i loop, then get the item at index identifier from there, and sum it to your running total

Thank you. So I would use a single for loop to iterate over the outer array but then how would I access the fixed index of a given position within the inner array? I’m early in my JavaScript journey so any direction/example you could offer would be greatly appreciated

you use bracket notation, you access the outer array with the index of the loop, and then the fixed index

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.