领导者数组 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/27 1:16:17

如果数字数组中的元素大于其右侧的所有元素,则该元素为领导者。我们需要编写一个 JavaScript 函数,该函数接受一个数字数组并返回满足领导者元素条件的所有元素的子数组。

例如 −

如果输入数组为:
[23, 55, 2, 56, 3, 6, 7, 1]
那么输出应该是:
[56, 7, 1]

让我们来编写该函数的代码 −

示例

const arr = [23, 55, 2, 56, 3, 6, 7, 1];
const leaderArray = arr => {
   const creds = arr.reduceRight((acc, val) => {
      let { max, res } = acc;
      if(val > max){
         res.unshift(val);
         max = val;
      };
      return { max, res };
   }, {
      max: -Infinity,
      res: []
   })
   return creds.res;
};
console.log(leaderArray(arr));

输出

控制台中的输出将是 −

[56, 7, 1]

相关文章


有用资源