On Educative.io I have an exercise whose solution uses an intermediate variable and I don't understand why I can't do it directly.
Exercise: Given an array of arrays, each of which contains a set of numbers, write a function that returns an array where each item is the sum of all the items in the sub-array. For example,
var numbers = [
[1, 2, 3, 4],
[5, 6, 7],
[8, 9, 10, 11, 12]
];
arraySum(numbers);
Would return the following array:
[10, 18, 42]
My solution:
var sums = [];
for(i=0; i<numbers.lenght; i++){
for(j=0; j<numbers[i].lenght; j++){
sums[i]= sums[i] + numbers[i][j] ;
}
}
return sums;
}
The correct reply is:
var arraySum = function(numbers) {
var sums = [];
var sum = 0;
var count = 0;
for (i = 0; i< numbers.length; i++){
for (j = 0; j< numbers[i].length;j++){
sum = sum + numbers[i][j]}
sums[i] = sum;
sum = 0;
}
return sums;
}
Why using the variable sum to write in the array sums ?
[ NaN, NaN, NaN ], because you add anumbertoundefinedinitially. Theirsumvariable is just one way of overcoming this problem. For your's this would work:sums[i] = (sums[i] || 0) + numbers[i][j];