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

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/19 15:40:17

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

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 ]

相关文章


有用资源