如何移除陣列中重複的屬性值 – 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.