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

Loại bỏ giá trị trùng lặp từ mảng chứa nhiều giá trị trong JavaScript


Giả sử mảng có giá trị trùng:

const listOfStudentName = ['John', 'Mike', 'John', 'Bob','Mike','Sam','Bob','John'];

Để loại bỏ giá trị trùng, dùng Set():

Ví dụ

const listOfStudentName = ['John', 'Mike', 'John', 'Bob','Mike','Sam','Bob','John']; console.log("The value="+listOfStudentName); const doesNotContainSameElementTwice = [...new Set(listOfStudentName)]; console.log("The Array="); console.log(doesNotContainSameElementTwice)

Chạy: node fileName.js. File demo42.js.

Kết quả

PS C:\Users\Amit\JavaScript-code> node demo42.js The value=John,Mike,John,Bob,Mike,Sam,Bob,John The Array= [ 'John', 'Mike', 'Bob', 'Sam' ]