Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách xóa giá trị thuộc tính trùng lặp trong mảng - JavaScript

Giả sử chúng ta có mảng sau:

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

Cần xóa giá trị thuộc tính trùng lặp (87 lặp lại, 98 lặp lại). Sử dụng map() kết hợp Set.

Ví dụ

Mã minh họa:

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);

Để chạy chương trình, sử dụng lệnh:

node tenFile.js

Tên file ở đây là demo292.js.

Kết quả

Đầu ra trên console:

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