陣列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