educative.io

Failing Test for Array Counts


#1

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;
}


#2

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.


#3

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


#4

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