Skip to main content

Command Palette

Search for a command to run...

Return Largest Numbers in Arrays - JavaScript Solution & Walkthrough

(05/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Published
2 min read
Return Largest Numbers in Arrays - JavaScript Solution & Walkthrough
B

I am a full stack developer passionate about web accessibility. When I'm not behind the screens, you'll likely find me reading or going for a 5K run.

05/16 Return Largest Numbers in Arrays

Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.

Remember, you can iterate through an array with a simple for loop, and access each member with array syntax arr[i].

function largestOfFour(arr) {

  return arr;
}

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

Credit: FreeCodeCamp.org

Understanding the Challenge

In this challenge, you will be provided with an array containing 4 sub-arrays. Your task is to create a function that return a new array. This new array should contain the largest numbers found in each of the sub-arrays.

Pseudocode

Given an array of sub-arrays
  iterate through the array
  For each iteration 
    return the largest number in the sub-array
Return an array of all largest numbers

Solving the Challenge

So here, we have a given array of sub-arrays. We need to iterate through this given array. There are a number of ways to do so. To keep things simple, let's use the .map() method.

We'll map through the given array. For every iteration, we'll have a subArray available to us. Using Math.max(), we can return the largest number in each subArray.

  const largeNums = arr.map(subArray => {
    return Math.max(...subArray);
  })

Note: We are using the ... spread operator to get all the numbers in the subArray.

Using the .map() method, we will get a new array made up of the the large numbers in each sub array.

We can then return this new array, in this case largeNums and our function is complete!

return largeNums;

Final Solution

function largestOfFour(arr) {
  const largeNums = arr.map(subArray => {
    return Math.max(...subArray);
  })
  return largeNums;
}

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

Congratulations!

You just cracked the fifth challenge in this series.

Cheers and happy coding!

JavaScript

Part 11 of 33

This JavaScript (JS) includes tutorials on various JS concepts. It also has solutions to common JS coding challenges.

Up next

Confirm the Ending - JavaScript Solution & Walkthrough

(06/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.