從 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 }
]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP