Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การหาผลรวม Unique Elements ในอาร์เรย์ (Sum Duplicates Together) ใน JavaScript

ภาพรวม

บทความนี้สาธิตวิธีรวมค่าที่ซ้ำกันในอาร์เรย์ โดยบวกค่า Duplicate เข้าด้วยกัน กลายเป็น Unique Values พร้อม Sum

ตัวอย่าง

Input:  [1, 3, 1, 3, 5, 7, 5, 4]
Process: 1+1=2, 3+3=6, 5+5=10, 7, 4
Output: [2, 6, 10, 7, 4] (ลำดับตาม First Occurrence)

การนำไปใช้

const mergeDuplicates = (arr) => {
  const map = arr.reduce((acc, val) => {
    acc.set(val, (acc.get(val) || 0) + val); // บวก Value ไม่ใช่ Count
    return acc;
  }, new Map());
  
  return Array.from(map, ([key, value]) => value);
};

console.log(mergeDuplicates([1, 3, 1, 3, 5, 7, 5, 4]));

ผลลัพธ์

[2, 6, 10, 7, 4]

หมายเหตุ: โค้ดต้นฉบับนับ Count แล้วคูณ (el[0] * el[1])

ผลลัพธ์เหมือนกันเพราะ: Count × Value = Sum of Values

วิธีการทันสมัย

const sumDuplicates = (arr) => 
  [...arr.reduce((map, val) => map.set(val, (map.get(val) || 0) + val), new Map()).values()];

// หรือ Object
const sumDuplicatesObj = (arr) => 
  Object.values(arr.reduce((acc, val) => (acc[val] = (acc[val] || 0) + val, acc), {}));

Preserve Order of First Appearance

const sumDuplicatesOrdered = (arr) => {
  const map = new Map();
  const order = [];
  
  for (const val of arr) {
    if (!map.has(val)) order.push(val);
    map.set(val, (map.get(val) || 0) + val);
  }
  
  return order.map(key => map.get(key));
};

การประยุกต์ใช้

  • Data Aggregation: Group By + Sum
  • Financial: Consolidate Transactions
  • Analytics: Event Count Weighted by Value
  • ETL: Deduplication with Aggregation

ข้อควรระวัง

  • Object Keys เป็น String: 1 และ '1' จะชนกัน
  • Map รองรับ Key ทุก Type
  • Floating Point Precision: 0.1 + 0.2 !== 0.3