Giả sử sau là mảng đối tượng của chúng ta với các bản sao:
var studentDetails = [
{studentId: 101},
{studentId: 104},
{studentId: 106},
{studentId: 104},
{studentId: 110},
{studentId: 106},
]
Sử dụng khái niệm Set để loại bỏ trùng lặp như trong mã dưới đây:
Ví dụ
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);
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Kết quả
Tên tệp của tôi là demo158.js. Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\JavaScript-code> node demo158.js
[ { studentId: 101 }, { studentId: 104 }, { studentId: 106 }, { studentId: 110 } ]