从 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