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)