如何移除数组中重复的属性值 – JavaScript?


假设 array 如下 −

var details = [
   {
      studentName: "John",
      studentMarks: [78, 98]
   },
   {
      studentName: "David",
      studentMarks: [87, 87]
   },
   {
      studentName: "Bob",
      studentMarks: [48, 58]
   },
   {
      studentName: "Sam",
      studentMarks: [98, 98]
   },
]

我们需要移除重复的属性值,即,上面重复了 87。我们需要移除它。

为此,请使用 map() 概念。

示例

以下是代码 −

var details = [
   {
      studentName: "John",
      studentMarks: [78, 98]
   },
   {
      studentName: "David",
      studentMarks: [87, 87]
   },
   {
      studentName: "Bob",
      studentMarks: [48, 58]
   },
   {
      studentName: "Sam",
      studentMarks: [98, 98]
   },
]
details.map(tempObj => {
   if (typeof (tempObj.studentMarks) == 'object') {
      tempObj.studentMarks = [... new Set(tempObj.studentMarks)]
      if (tempObj.studentMarks.length == 1) {
         tempObj.studentMarks = tempObj.studentMarks[0]
      }
   }
});
console.log(details);

要运行上述程序,你需要使用以下命令 −

node fileName.js.

这里,我的文件名是 demo292.js。

输出

这将在控制台上生成以下输出 −

PS C:\Users\Amit\javascript-code> node demo292.js
[
   { studentName: 'John', studentMarks: [ 78, 98 ] },
   { studentName: 'David', studentMarks: 87 },
   { studentName: 'Bob', studentMarks: [ 48, 58 ] },
   { studentName: 'Sam', studentMarks: 98 }
]

更新时间: 09-11-2020

739 次浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告
© . All rights reserved.