สมมติว่าเรามีอาร์เรย์ของอาร์เรย์ แต่ละอันมีตัวเลขบ้าง undefined และ null บ้าง เราต้องสร้างอาร์เรย์ใหม่ที่มีผลรวมของแต่ละซับอาร์เรย์เป็นสมาชิก และค่า undefined และ null ควรนับเป็น 0
อาร์เรย์ตัวอย่าง
const arr = [[ 12, 56, undefined, 5 ], [ undefined, 87, 2, null ], [ 3, 6, 32, 1 ], [ undefined, null ]];
โค้ดเต็ม
ตัวอย่าง
const arr = [[
12, 56, undefined, 5
], [
undefined, 87, 2, null
], [
3, 6, 32, 1
], [
undefined, null
]];
const newArr = [];
arr.forEach((sub, index) => {
newArr[index] = sub.reduce((acc, val) => (acc || 0) + (val || 0));
});
console.log(newArr);
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
[ 73, 89, 42, 0 ]