ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของตัวเลข (บวกและลบ) ฟังก์ชันของเราควรคำนวณและส่งคืนผลรวมของจำนวนบวกทั้งหมดที่มีอยู่ในอาร์เรย์
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [5, -5, -3, -5, -7, -8, 1, 9];
const sumPositives = (arr = []) => {
const isPositive = num => typeof num === 'number' && num > 0;
const res = arr.reduce((acc, val) => {
if(isPositive(val)){
acc += val;
};
return acc;
}, 0);
return res;
};
console.log(sumPositives(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
15