## Algorithm 05: Return Largest Numbers in Sub-Arrays

This algorithm introduces the notion of nested loops and comparisons. We need to loop through each item in the array, then in turn loop through the sub-array and compare if the current value is greater then the last, if so push that value to a new array ‘resultArr’ and return the new array when the loops complete.

Now that’s a mouthful.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /* Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays. */ const largestOfEachArray = (arr) => { let resultArr = []; for(let i=0; i<arr.length; i++) { let highestNum = 0; let innerArray = arr[i]; for(let i=0; i<innerArray.length; i++){ if (innerArray[i] > highestNum){ highestNum = innerArray[i]; } } resultArr.push(highestNum); } return resultArr; } largestOfEachArray([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]); // returns [27,5,39,1001] largestOfEachArray([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]); // returns [9, 35, 97, 1000000] |