ภาพรวม
บทความนี้สาธิตวิธีหาผลรวมของคอลัมน์ (Column Sum) ในอาร์เรย์ 2 มิติที่มีความยาวแถวไม่เท่ากัน (Jagged Array)
ตัวอย่าง
Input: [
[43, 2, 21],
[1, 2, 4, 54],
[5, 84, 2],
[11, 5, 3, 1]
]
Output: [60, 93, 30, 54] // คอลัมน์ที่ 4 มีแค่ 2 แถว: 54 + 1 = 55? Wait...
// 43+1+5+11=60, 2+2+84+5=93, 21+4+2+3=30, 54+1=55
การนำไปใช้
const sumArray = (array) => {
const newArray = [];
array.forEach(sub => {
sub.forEach((num, index) => {
if (newArray[index] !== undefined) {
newArray[index] += num;
} else {
newArray[index] = num;
}
});
});
return newArray;
};
const arr = [
[43, 2, 21],
[1, 2, 4, 54],
[5, 84, 2],
[11, 5, 3, 1]
];
console.log(sumArray(arr)); // [60, 93, 30, 55]
ผลลัพธ์
[60, 93, 30, 55]
วิธีการทันสมัย (ES6+)
// ใช้ reduce
const sumColumnsReduce = (matrix) =>
matrix.reduce((sums, row) => {
row.forEach((val, i) => sums[i] = (sums[i] || 0) + val);
return sums;
}, []);
// ใช้ transpose + map (สำหรับ Rectangular Matrix)
const sumColumnsTranspose = (matrix) => {
const maxCols = Math.max(...matrix.map(r => r.length));
return Array.from({ length: maxCols }, (_, i) =>
matrix.reduce((sum, row) => sum + (row[i] || 0), 0)
);
};
การประยุกต์ใช้
- Data Analysis: Column-wise Aggregation
- Spreadsheet Calculations
- Image Processing: Column Projection
- Time Series: Sum Across Multiple Series
- Matrix Operations
ข้อควรระวัง
- Jagged Arrays: คอลัมน์สั้นกว่าจะถูกนับแค่ค่าที่มี
- Non-numeric Values: ควรกรองหรือแปลงก่อน
- Sparse Arrays: ช่องว่าง (undefined) จะถูกข้าม
เวอร์ชัน Type-Safe (TypeScript Style)
const sumColumnsTyped = (matrix: number[][]): number[] => {
const maxCols = Math.max(0, ...matrix.map(r => r.length));
const sums = new Array(maxCols).fill(0);
for (const row of matrix) {
for (let i = 0; i < row.length; i++) {
sums[i] += row[i];
}
}
return sums;
};