Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หาค่ามากที่สุดในแต่ละอาเรย์ย่อยด้วย reduce() และ Math.max()

ใช้ reduce() ร่วมกับ Math.max(...array) หาค่าสูงสุดของแต่ละ Sub-array

ตัวอย่างโค้ด

const getBiggestNumberFromArraysPassed = allArrays => 
    allArrays.reduce((maxValue, maxCurrent) => {
        maxValue.push(Math.max(...maxCurrent));
        return maxValue;
    }, []);

console.log(getBiggestNumberFromArraysPassed([[45, 78, 3, 1], [50, 34, 90, 89], [32, 10, 90, 99]]));

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo94.js)

ผลลัพธ์

[ 78, 90, 99 ]