数组JavaScript中的先导
如果数组 Number 中的一个元素大于其右侧的所有元素,则该元素为先导。我们需要编写一个 JavaScript 函数,该函数接受一个 Number 数组并返回所有元素的子数组,这些元素满足先导元素的标准。
例如,−
If the input array is: [23, 55, 2, 56, 3, 6, 7, 1] Then the output should be: [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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP