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: 2020-09-18T12:56:22+05:30

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements