從 JavaScript 中的物件陣列中刪除重複項的最佳方式是什麼?


假設我們的物件陣列如下所示,其中包含重複項 −

var studentDetails=[
   {studentId:101},
   {studentId:104},
   {studentId:106},
   {studentId:104},
   {studentId:110},
   {studentId:106},
]

如下所示,利用 set 概念來刪除重複項 −

示例

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.

輸出

此處,我的檔名為 demo158.js。這將生成以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo158.js
[
   { studentId: 101 },
   { studentId: 104 },
   { studentId: 106 },
   { studentId: 110 }
]

更新於:2020 年 9 月 12 日

180 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.