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.
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.