1

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 ?

1
  • 1
    If you fix the typo, your code results in [ NaN, NaN, NaN ], because you add a number to undefined initially. Their sum variable is just one way of overcoming this problem. For your's this would work: sums[i] = (sums[i] || 0) + numbers[i][j]; Commented Jul 21, 2020 at 7:44

2 Answers 2

1

I wouls suggest a slightly different approach by

  • declaring all variables, as well the ones for the loop,
  • removing unnecessary/unused variables,
  • initialize a value at an index outside of the most inner loop,
  • update the value at index with the value.

var arraySum = function(numbers) {
        const sums = [];
        for (let i = 0; i < numbers.length; i++) {
            sums[i] = 0;
            for (let j = 0; j < numbers[i].length; j++) {
                sums[i] += numbers[i][j];
            }
        }
        return sums;
    };

console.log(arraySum([[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12]]));

Sign up to request clarification or add additional context in comments.

Comments

1

Why using the variable sum to write in the array sums ?

It's slightly more efficient, in theory, to use that local variable in the inner loop rather than going back to the array every time for the current value. It's unlikely to make a difference in real-world code, though. Also, if they're going to do that, they might want to do it with numbers[i] as well.

But note that your solution has a typo: lenght instead of length. If your solution was rejected, it may be down to that rather than the sum thing. Also, you need sum[i] = 0; at the top of the body of the inner loop, since otherwise you're using sum[i] when it doesn't have a value (so you'll get undefined, which means the addition will result in NaN).


But I'm sorry to see that that "correct" answer has code relying on The Horror of Implicit Globals (it never declares i). Also that it uses inconsistent bracing style (and that awful }-at-the-end-of-the-line in one place, which I'd strongly urge you not to adopt). It also never uses count for anything. If that's really the "right answer" they give, you might consider a different tutorial or course.

2 Comments

I fix the typo 'lenght' and the output is 'NaN,NaN,NaN' .
@cibirsk - I don't have any specific one I would recommend. (The NaN is because of the issue with initializing sum[i], I edited the answer a few minutes before your comment, you may have been seeing the older copy.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.