Return the maximum number in each array using map JavaScript


We have an array of arrays of Numbers like this one −

const arr = [
   [12, 56, 34, 88],
   [65, 66, 32, 98],
   [43, 87, 65, 43],
   [32, 98, 76, 83],
   [65, 89, 32, 54],
];

We are required to write a function that maps over this array of arrays and returns an array that contains the maximum (greatest) element from each subarray.

Therefore, let’s write the code for this function −

Example

const arr = [
   [12, 56, 34, 88],
   [65, 66, 32, 98],
   [43, 87, 65, 43],
   [32, 98, 76, 83],
   [65, 89, 32, 54],
];
const findMax = arr => {
   return arr.map(sub => {
      const max = Math.max(...sub);
      return max;
   });
};
console.log(findMax(arr));

Output

The output in the console will be −

[
   88,
   98,
   87,
   98,
   89
]

Updated on: 26-Aug-2020

563 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements