在 JavaScript 中从对象数组中删除重复项的最佳方法是什么?

javascriptweb developmentobject oriented programming更新于 2025/11/17 16:12:17

假设以下是包含重复项的对象数组−

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

使用集合的概念删除重复项,如以下代码所示 −

示例

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 }
]

相关文章


有用资源