Giả sử sau đây là mảng đối tượng của chúng ta có 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 tập hợp để loại bỏ các bản sao như trong đoạn 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.
Đầu ra
Ở đây, tên tệp của tôi là demo158.js. Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo158.js
[
{ studentId: 101 },
{ studentId: 104 },
{ studentId: 106 },
{ studentId: 110 }
]