Return Largest Numbers in Arrays - Feedback

Return Largest Numbers in Arrays - Feedback



function largestOfFour(arr) {
  var finalArray = []; //create empty array to store largest number of each subarray

  for (var i = 0; i < arr.length; i++) { //loop through arr
    var largestNumber = arr[i][0]; //initialize largest number
    for (var j = 0; j < arr[i].length; j++) { //loop through subarray
      if (arr[i][j] > largestNumber) { // Find largest number in subarray
        largestNumber = arr[i][j];
    } finalArray.push(largestNumber); //Push largest number to finalArray
  } return finalArray;

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

Does my code make sense to you and is it straightforward? How did you do?



For me it makes perfectly sense as it is the “basic” straightforward way to solve this challenge in my mind.

I solved it in a different way using map/reduce. For me it seems more intuitive like words describing the solution instead of an algorithm describing the solution which requires few seconds until you can completely understand.

In your situation you can use the map function to map from array to subarray and you can use the reduce function to reduce each subarray to the largest number in this array.


I don’t know the actual task, but according to your code, getting the largest Number for each subarray you could also do something like this:

function largestOfFour (arr) {
  return arr.reduce(function(final, sub) {
    return final.concat(Math.max(...sub));
  }, []);

OR with Arrow-Functions

const largestOfFour = arr => arr.reduce((final, sub) => final.concat(Math.max(...sub)), []);

##Some Links:
MDN: Array.reduce
MDN: Math.max()
MDN: Arrow functions
MDN: Spread operator

If you need some more explanation, let me know :wink:


Probably the simplest solution:

function get_max(arr) {

const largestOfFour = (xs) => Math.max( ...[].concat(...xs) )


Thank you! I will most definitely try that out!