How to find the largest numbers from each subarray in JavaScript?

By IncludeHelp Last updated : January 21, 2024

Problem statement

Given an array with subarrays (i.e., an array within arrays (nested array), you have to write JavaScript code to find the largest numbers from each subarray.

Finding the largest numbers from each subarray

To find the largest numbers from each subarray, you can use the Math.max.apply() method by passing null and an array containing subarrays along with the return statement and array.map() method.

JavaScript code to find the largest numbers in a subarray

The below example finds the largest numbers in a subarray arr.

```// Defining function to find the largest numbers
// from each subarray
function largest(arr) {
return arr.map(function (arr) {
return Math.max.apply(null, arr);
});
}

// create an array with subarrays
arr = [
[10, 50, 20, 30],
[1, 2, 3, 2],
[444, 888, 999, 555],
[108, 1008]
]

// calling the function & printing the result
console.log(largest(arr));
```

Output

The output of the above code is:

```[50, 3, 999, 1008]
```
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics: