educative.io

Failing Test for Array Counts

My code is not passing, and i’m very confused…

var arraySum = function(numbers) {
var sums = [];
//write your code here
for(var i = 0; i < numbers.length; i++) {
sums += numbers[i];
for(var j = 0; j < numbers[i].length; j++) {
sums += numbers[i][j];
}
}
return sums;
}

Hi @jlc,

This is Fatimah Abdullah from Educative. Thank you for reaching out to us!

In regards to your code, there are a few logical issues with it. Firstly, the variable sums is an array. And, in the output we expect it to have values associated with each row of the numbers array. So for example, the sum of the 0th row of numbers should be stored in 0th index of the sums array.

In your code, in the outer loop, you are adding the whole ith row to the sums.

This will just append the row to sums. Instead, we should be initializing the ith index of sums with 0. Like so:

sum[i] = 0;

Next, in the inner loop, you are again adding directly into the sums variable. It should be in the ith index of the sums.

The complete solution should look something like the following:

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

I hope this helps. If you have any questions about this solution please feel free to reach out to me.

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative.

1 Like

please can u explain the concept of nested arrays to me please… i need help with it .

Hi @Isaac_Osei_Owusu-Ans,

The concept of Nested Arrays in Javascript basically means that an array can have other arrays as elements. This is similar to the multidimensional arrays that you might see in other languages such as C++ and Java.
An example for nested arrays:

var classes = new Array(); //an array of classes
classes[0] = new Array("Jason", "Eric", "Emily"); // This class has an array of 3 students
classes[1] = new Array("Eli", "Alison", "Carter", "Andrew"); // This class has an array of 4 students

I hope this explanation helps.

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative

1 Like

Hi @FatimahAbdullah. Although I get the idea of nesting arrays I was not able to solve the exercise which saddens me greatly. I was forced to look up here for hints and I found your solution which I understand. However, when I check the solution in tutorial it is different and this one I do not follow. Can you please explain what is “var count” there? It is not used anywhere else in the code. I was not able to find a sufficient explanation in Google. Also why at the end you repeat “sum=0”? At the beginning there already is “var sum = 0”. Isn’t it enough? Looking forward to feedback.