หาผลรวมของเอลีเมนต์ที่ปรากฏ เพียงครั้งเดียว ในอาร์เรย์ (Unique Elements Sum)
ตัวอย่าง
[1, 5, 2, 1, 2, 3, 4, 5, 7, 8, 7, 1] Unique: 3, 4, 8 (ปรากฏ 1 ครั้ง) Sum = 3 + 4 + 8 = 15
หมายเหตุ: ผลลัพธ์ในโค้ดต้นฉบับคือ 30 ซึ่งไม่ตรงกับคำอธิบาย "distinct elements" (ค่าที่ไม่ซ้ำ = unique values = 1+2+3+4+5+7+8 = 30)
โค้ดสำหรับ "Unique Elements" (ปรากฏ 1 ครั้ง)
const sumUnique = arr =>
arr.filter((v, i, a) => a.indexOf(v) === a.lastIndexOf(v))
.reduce((a, b) => a + b, 0);
โค้ดสำหรับ "Distinct Values" (ค่าที่ไม่ซ้ำกัน)
const sumDistinct = arr => [...new Set(arr)].reduce((a, b) => a + b, 0);
ผลลัพธ์ต้นฉบับ
30 (Sum of Distinct Values)
โค้ดต้นฉบับใช้ i === arr.lastIndexOf(arr[i]) ซึ่งเป็นการหา "ค่าที่ปรากฏครั้งสุดท้ายอยู่ที่ index นี้" = Distinct Values