- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Arrays vs Set in JavaScript.
The Set data type was introduced in ES2015 and the difference between array and set is that while an array can have duplicate values a set can’t. Elements can be accessed in array using index which isn’t possible in Set since it uses keys and elements can be traversed only in the way they were entered.
Following is the code displaying the difference between array and Set in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result,.sample { font-size: 18px; font-weight: 500; color: rebeccapurple; } .result { color: red; } </style> </head> <body> <h1>Array Vs Set</h1> <div class="sample"></div> <div class="result"></div> <button class="Btn">Convert</button> <h3>Click on the above button to convert the above array into a set</h3> <script> let resultEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let arr = [2, 3, 4, 2, 3, 4, "A", "A", "B", "B"]; sampleEle.innerHTML = "arr = " + arr; document.querySelector(".Btn").addEventListener("click", () => { let set1 = new Set(arr); resultEle.innerHTML = "set1 = " + [...set1] + "<br>"; }); </script> </body> </html>
Output
The above code will produce the following output −
On clicking the ‘Convert’ button −
On clicking the ‘Display’ button −
- Related Articles
- How to workaround Objects vs arrays in JavaScript for key/value pairs?
- Set vs HashSet vs TreeSet in Java
- Set vs Map in C++ STL
- set vs unordered_set in C++ STL(3)
- Flattening arrays in JavaScript
- Special arrays in JavaScript
- Chunking arrays in JavaScript
- d vs D in JavaScript?
- Window.onload vs onDocumentReady in javascript
- Push() vs unshift() in JavaScript?
- Undeclared vs Undefined? In JavaScript
- innerHTML vs innerText in JavaScript.
- Const vs Let in JavaScript.
- Deviations in two JavaScript arrays in JavaScript
- Javascript typed arrays

Advertisements