Cho mảng các mảng con chứa số, undefined, null. Tạo mảng mới chứa tổng mỗi mảng con, coi undefined/null như 0.
Mảng mẫu:
const arr = [[ 12, 56, undefined, 5 ], [ undefined, 87, 2, null ], [ 3, 6, 32, 1 ], [ undefined, null ]];
Ví dụ
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);Kết quả
Đầu ra console:
[ 73, 89, 42, 0 ]