Build maximum array based on a 2-D array - JavaScript


Let’s say, we have an array of arrays of Numbers like below −

const arr = [
  [1, 16, 34, 48],
  [6, 66, 2, 98],
  [43, 8, 65, 43],
  [32, 98, 76, 83],
  [65, 89, 32, 4],
];

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.

So, for the above array, the output should be −

const output = [
   48,
   98,
   65,
   83,
   89
];

Example

Following is the code to get the greatest element from each subarray −

const arr = [
   [1, 16, 34, 48],
   [6, 66, 2, 98],
   [43, 8, 65, 43],
   [32, 98, 76, 83],
   [65, 89, 32, 4],
];
const constructBig = arr => {
   return arr.map(sub => {
      const max = Math.max(...sub);
      return max;
   });
};
console.log(constructBig(arr));

Output

This will produce the following output in console −

[ 48, 98, 65, 98, 89 ]

Updated on: 18-Sep-2020

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements