从包含多个值的数组中删除相同的值 JavaScript
javascriptweb developmentobject oriented programming
假设以下是具有相似值的数组 −
const listOfStudentName = ['John', 'Mike', 'John', 'Bob','Mike','Sam','Bob','John'];
要从数组中删除相似的值,请使用 set() 的概念。以下是代码 −
示例
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)
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里,文件名是 demo42.js。
输出
这将产生以下输出 −
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' ]