[Challenge] Return Largest Numbers in ArraysPassed, recursive solution

Link.

Can someone explain this code?

const largestOfFour = (arr, finalArr = []) =>
  !arr.length ? finalArr : largestOfFour(arr.slice(1), finalArr.concat(Math.max(...arr[0])))

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

Here’s the same code, but much more verbose. Maybe it helps in understanding what’s happening:

function largestOfFour(arr, finalArr=[]){

  // base case of recursion
  if (arr.length === 0){
    return finalArr

  } else {
    
    let maxOfSubArray = Math.max(...arr[0]);  // biggest value in the first subarray
    let newFinalArr = finalArr.concat(maxOfSubArray); // adds that value to the final array

    let newArr = arr.slice(1); // newArr is arr but without the first subarray

    return largestOfFour(newArr, newFinalArr)
  }
}

In other words - in each step of the recursion

  • you look for the maximum in the first subarray
  • add that value to the final array that’s holding all the maximums
  • call the function again, with an array where the first subarray isn’t present anymore
  • once that array is empty, you return the final array

I much prefer this solution though, it doesn’t use fancy recursion but it’s much clearer what’s happening:

Solution with map and reduce
function largestOfFour(arr) {
  return arr.map(subArr => subArr.reduce((acc, item) => item > acc ? item : acc))
}
1 Like

Ah, snap

function largestOfFour (arr, finalArray = []) {
  if (arr.length === 0) {
    return finalArray;
  } else {
    let currentSubarray = arr[0];
    let largestValueInCurrentSubarray = Math.max(...currentSubarray);
    // Push the largest value into the output:
    finalArr.push(largestValueInCurrentSubarray);

    // Now run the function again on the remaining subarrays:
    let remainingSubarrays = arr.slice(1);
    return largestOfFour(remainingSubarrays, finalArr);
  }
1 Like

Hehe. I saw you typing but had already finished writing the longer version. I prefer your variable names though.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.