JavaScript根据二维数组构建最大数组方法详解

2023年11月29日11:56:50

假设我们有一个数字数组,如下所示:

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

我们需要编写一个映射到该数组数组并返回一个包含每个子数组中最大(最大)元素的数组的函数。

因此,对于上述数组,输出应为-

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

示例

以下是从每个子数组中获取最大元素的代码-

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));

输出结果

这将在控制台中产生以下输出-

[ 48, 98, 65, 98, 89 ]

  • 更新时间:2023年11月29日11:56:50 ,共 546 字。