Seems like it should work!?!?

Seems like it should work!?!?
0

#1

Tell us what’s happening:
This passes all the tests provided yet doesn’t clear the challenge. Am I doing something wrong? I have very limited knowledge of the .splice() method, discovered it while looking for an answer to this. Maybe that’s what’s wrong, but again, the code passes all the tests.

Your code so far

function largestOfFour(arr) {
  for(var i = 0; i < arr.length; i++) {
    arr[i].sort(function(a, b){return b-a;});
    arr[i].splice(-3, 3);
    
  }
  return arr;
}

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393.

Link to the challenge:


#2

When I run your code through the tests, only the first one.

The problem with your function is that it should be returning an array of numbers. Instead it returns an array of arrays.

For example:

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

should return: [5, 27, 39, 1001]
but instead returns [ [ 5 ], [ 27 ], [ 39 ], [ 1001 ] ]


#3

Wow, what a silly oversight. Is there a way to keep this code and just remove the sub-arrays? I can’t seem to find one. Back to the drawing board, thank you very much!.


#4

To keep most of your solution, you could declare an empty array called newArray and since you are sorting each individual array from least to greatest you could use newArray.push(firstElementOfArr[i]) after the sort during each iteration. Finally you would return newArray at the very end.

Review push documentation here.

You just need to figure out how to reference the first element of arr[i]


#5

This returns the right answers, as far as I can tell, but still doesn’t complete the challenge.

var array = [];
function largestOfFour(arr) {
  for(var i = 0; i < arr.length; i++) {
    arr[i].sort(function(a, b){return b-a;});
    arr[i].splice(-3, 3);
    array.push(arr[i][0]);
    
  }
  
  return array;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

#6

I guess I don’t need the .splice() anymore, still searching, still confused, lol. Thanks for all the help though!


#7

No need for splice on this solution.


#8

Also, do not declare the array = [] outside the function, because you will not pass all the tests.