Return largest numbers in arrays

Hey countercoded,

Sure, I’ll give it a go.

I actually posted an overly-long post about array methods (including map) here:

In a nutshell, the map method returns a value for each element in an array. In the case of this challenge, you have an array of arrays (an array where each element in the array is itself an array). Those arrays contain, in turn, numbers.

The challenge is to return an array containing the largest number of each element in the main array.

The .map() method goes over each element in an array returns an array of results, so that’s useful.
The Math.max method accepts arguments which are numbers and returns the largest, so that’s useful as well.
The .apply() method is available on functions and will call the function allowing you to pass in an array which it will in turn use as arguments to the function being “applied”. That means you can pass in an array of numbers and Math.max() will return the largest.

Hopefully that makes sense.

Here are some references:

If you’re brand new to programming, this may be a bit much. But at the very least, it’s good to know tools like this exist so that you can explore.

Hope this helped!

Regards,
Micheal

3 Likes

Here’s my solution, with a while loop:

function largestOfFour(arr) {
  var largestNumArray = [];
  var i = 0;
  while (i < arr.length) {
    arr[i].sort(function(a, b) {return a - b;});
    largestNumArray.push(arr[i][3]);
    i++;    
  }
  return largestNumArray;
}

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

Hi all, just thought I’ll share my code here as well :slight_smile: Cheers!

function largestOfFour(arr) {
  
  // variable to contain new sorted array
  var biggestNumArr = [];
  
  // for loop to loop through each outer array element
  for (var i = 0; i < arr.length; i++) {
    
    // inner array elements sorted in reverse, and then
    // pushed into biggestNumArr
    biggestNumArr.push(arr[i].sort(function (a, b) {
      return b - a;
    })[0]);
  
  }
  
  return biggestNumArr;
}

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