The main difference between JavaScript Set and Array is that an array can have duplicate values a set can’t. The array is a type of structure representing a block of data (numbers, objects, etc…) allocated in consecutive memory.
[1,2,3,2]
Set is an abstract data type that contains only distinct elements/objects without the need of being allocated orderly by index.
{1,2,3}
The array is considered an “indexed collection” type of data structure, while the Set is considered a “keyed collection”.
JavaScript Set vs array
Simple example code converts the array to set.
<!DOCTYPE html>
<html>
<body>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">Convert</button>
<script>
let r = document.querySelector(".result");
let s = document.querySelector(".sample");
let arr = [2, 3, 4, 2, 3, 4, "A", "A", "B", "B"];
s.innerHTML = "Array = " + arr;
document.querySelector(".Btn").addEventListener("click", () => {
let set1 = new Set(arr);
r.innerHTML = "Set = " + [...set1] + "<br>";
});
</script>
</body>
</html>
Output:
Javascript Set vs. Array performance
Tested adding, iterating, and removing elements from both an array and a set. Ran a “small” test, using 10 000 elements, and a “big” test, using 100 000 elements. Here are the results.
Adding elements to a collection
It would seem that the .push
array method is about 4 times faster than the .add
set method, no matter the number of elements being added.
Iterating over and modifying elements in a collection
Used a for
loop to iterate over the array and a for of
loop to iterate over the set. Again, iterating over the array was faster.
Removing elements from a collection
Now, this is where it gets interesting. I used a combination of a for
loop and .splice
to remove some elements from the array and I used for of
and .delete
to remove some elements from the set. For the “small” tests, it was about three times faster to remove items from the set (2.6 ms vs 7.1 ms) but things changed drastically for the “big” test where it took 1955.1 ms to remove items from the array while it only took 83.6 ms to remove them from the set, 23 times faster.
Source & Read more: https://stackoverflow.com/questions/39007637/javascript-set-vs-array-performance
Do comment if you have doubts or suggestions on this difference topic between array and set.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version