ใช้ Set เก็บค่า key ที่เจอแล้ว เพื่อกรองออบเจกต์ซ้ำ
วนลูปอาร์เรย์ ตรวจสอบ key ใน Set ถ้ายังไม่มี เพิ่มใน Set และ push เข้าผลลัพธ์
ตัวอย่างโค้ด
var studentDetails = [
{ studentId: 101 },
{ studentId: 104 },
{ studentId: 106 },
{ studentId: 104 }, // ซ้ำ
{ studentId: 110 },
{ studentId: 106 } // ซ้ำ
];
const distinctValues = new Set();
const withoutDuplicate = [];
for (const tempObj of studentDetails) {
if (!distinctValues.has(tempObj.studentId)) {
distinctValues.add(tempObj.studentId);
withoutDuplicate.push(tempObj);
}
}
console.log(withoutDuplicate);
วิธีรัน
node fileName.js
ผลลัพธ์
[
{ studentId: 101 },
{ studentId: 104 },
{ studentId: 106 },
{ studentId: 110 }
]
คำอธิบาย
Setเก็บค่า unique ได้ O(1) lookup- เวลา O(n) เร็วกว่า filter + indexOf (O(n²))
- รักษาลำดับของ item แรกที่เจอ (first occurrence)
วิธีทันสมัย ES6+ (One-liner)
// ใช้ Map เก็บ key ล่าสุด แล้วดึง values
const unique = [...new Map(studentDetails.map(o => [o.studentId, o])).values()];
// หรือ filter กับ Set
const seen = new Set();
const unique2 = studentDetails.filter(o =>
seen.has(o.studentId) ? false : seen.add(o.studentId)
);