Stuck with this code in javascript

somebody please tell me what is the problem with this code ,it is a code to find the largest of the four arrays.I have mentioned

var farray = [];
var ans = [];
function largestOfFour(arr) {
for (i=0;i<arr.length;i++){
  return ans;
largestOfFour(([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]));

Tests to satisfy:-

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000]

You should read the MDN page on array.sort, specifically the syntax section first, and then read some of the examples. You’ll get it.

Edit: Hint - pay special attention to the comparator function.

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


One of your problems is that you arrays farray[ ] and ans[ ] are being used for each of the tests but are never emptied after tests. The data from the previous test is still in those arrays when you run the next test.

You’ll either need to make those local to the function or have some way to empty them at the start of each test. Local to function is probably the cleaner way - that way only data going in to function is parameters and only data out is return value.

Another problem is that Array sort() method doesn’t sort numbers the way most would expect. You can read up on sort (link in previous post). sort() can be modified to sort numbers in numerical order or possibly you could use a method other than sort to determine the largest of the array.

//not what you would expect
var myArray = [8,31,200,17];
console.log(myArray.sort());  //[17,200,31,8]

Good luck

will surely keep that in mind next time for sure.

@alhazen1 @vipatron thanx to both of you as I have realized the problem, I can now implement it the correct way and got a clearer view of the sort method.

1 Like