Returning a sorted list of sub-arrays however only one sub-array is returned

Tell us what’s happening:
Hi Im struggling to understand why this array only returns the last sub array, can someone explain to me how I would be able to make it return all four sub-arrays.

Your code so far

function largestOfFour(arr) {
  // You can do this!
var sortedArray=[];
 var redArray=[];
 for (i=0;i<arr.length;i++){
 sortedArray=arr[i].sort(function(a,b){return b-a;});}
  

  
  return sortedArray;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/604.5.6 (KHTML, like Gecko) Version/11.0.3 Safari/604.5.6.

Link to the challenge:
https://www.freecodecamp.org/challenges/return-largest-numbers-in-arrays

The returned variable sortedArray is getting updated in the loop each time.
Put your code in http://pythontutor.com/ and you will see.

1 Like

During each iteration of the for loop, you are reassigning a different value to it with the following code:

		sortedArray = arr[i].sort(function(a, b) {
			return b - a;
		});

Your function returns the last value sortedArray was assigned, which is the last sub array in arr.

You are not supposed to be returning one of the sub arrays. You are supposed to be returning a new array containing the largest value of each subarray.

You first need to figure out how to get the largest value in each sub array, then you could push this value into a new array which you would need to declare before the for loop starts.

1 Like

Yeah I have just added the last part which was to reduce the sub-arrays by just taking the first value of each array, thanks.