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
You can use map reduce array functions
you can get exactly the same result with nested for loops
Please see for more details
Array.prototype.map
Array.prototype.reduce
for…of
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:
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.