ภาพรวม
บทความนี้สาธิตวิธีคำนวณผลรวมค่าสัมบูรณ์ (Absolute Sum) ของอาร์เรย์ที่มีทั้งตัวเลขบวกและลบ โดยไม่ใช้ Library Function
ตัวอย่าง
Input: [1, -5, -34, -5, 2, 5, 6]
Output: 58 (|1| + |-5| + |-34| + |-5| + |2| + |5| + |6| = 58)
การนำไปใช้
const absoluteSum = (arr) => {
let res = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < 0) {
res += arr[i] * -1; // หรือ -arr[i]
} else {
res += arr[i];
}
}
return res;
};
console.log(absoluteSum([1, -5, -34, -5, 2, 5, 6])); // 58
ผลลัพธ์
58
วิธีการทันสมัย (ES6+)
// ใช้ Math.abs
const absoluteSumModern = (arr) =>
arr.reduce((sum, val) => sum + Math.abs(val), 0);
// ใช้ map + reduce
const absoluteSumMap = (arr) =>
arr.map(Math.abs).reduce((a, b) => a + b, 0);
// One-liner
const absoluteSumOneLine = (arr) =>
arr.reduce((s, v) => s + (v < 0 ? -v : v), 0);
การประยุกต์ใช้
- Signal Processing: Total Variation
- Statistics: Mean Absolute Deviation (MAD)
- Machine Learning: L1 Regularization (Lasso)
- Finance: Total Transaction Volume (ไม่สนใจทิศทาง)
- Error Metrics: MAE (Mean Absolute Error)
ข้อควรระวัง
- Math.abs(-2147483648) === -2147483648 (Integer Overflow ใน 32-bit แต่ JS ใช้ 64-bit Float)
- BigInt: ต้องใช้คำสั่งเฉพาะ (Math.abs ไม่รองรับ BigInt)
- Non-numeric values: ควรกรองหรือแปลงก่อนคำนวณ
เวอร์ชันรองรับ BigInt
const absoluteSumBigInt = (arr) =>
arr.reduce((sum, val) => sum + (val < 0 ? -val : val), 0n);