องค์ประกอบในอาร์เรย์ของ Numbers จะเป็นผู้นำถ้ามีค่ามากกว่าองค์ประกอบทั้งหมดทางด้านขวา เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของ Numbers และส่งคืนอาร์เรย์ย่อยขององค์ประกอบทั้งหมดที่ตรงตามเกณฑ์ของการเป็นองค์ประกอบผู้นำ
ตัวอย่างเช่น −
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]