基于二维数组构建最大数组——JavaScript


假设我们有一个如下 Number 的数组数组:

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 ]

更新于:18-9 月-2020

93 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.