@codename11 first please first point out mistakes in my given code, once challenge will get solved and my concept will get clear. I will also check your advance method.
function largestOfFour(arr) {
let result = [] ;
for (let i = 0 ; i < arr.length ; i++){
let max = arr[i][0];
for(let j = 0 ; j < arr[i].length ; j++){
if (arr[i][j] > max ){
max = arr[i][j] ;
}
}
result.push(max);
}
return result;
}
let max = arr[i][0]; is the initial value to the max element in each subarray, if you make it 0 it will not work for subarray with all elements are negative.
and this result.push(max) ; is : to push the max of each subarray one by one to the result array.
Hi
Look at this case of sub-array [-2, -3, -4] the max is -2 but it is less than max=0,
so you will end up by 0 which is wrong.
so we assume that the max is the first element of the sub-array : arr[i][0], or any other
element of the sub-array, but we are not sure if our sub-array passed as argument to our function contain more than one element.
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
[4,5,1,3] : is called sub-array because it is inside an other array.
why we choose arr[i][0] as initial value for the max , look at this link :