Ok, I have tested adding, iterating and removing elements from both an array and a set. I 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

For this part of the test I 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. This time it would seem that it is exponentially so as it took twice as long during the "small" tests and almost four times longer during the "big" tests.

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.

Conclusions

At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is.

I played around with some hybrid scenarios where an array was created and populated and then converted into a set where some elements would be removed, the set would then be reconverted into an array. Although doing this will give much better performance than removing elements in the array, the additional processing time needed to transfer to and from a set outweighs the gains of populating an array instead of a set. In the end, it is faster to only deal with a set. Still, it is an interesting idea, that if one chooses to use an array as a data collection for some big data that doesn't have duplicates, it could be advantageous performance wise, if there is ever a need to remove many elements in one operation, to convert the array to a set, perform the removal operation, and convert the set back to an array.

Array code:

var timer = function(name) {
  var start = new Date();
  return {
    stop: function() {
      var end = new Date();
      var time = end.getTime() - start.getTime();
      console.log('Timer:', name, 'finished in', time, 'ms');
    }
  }
};

var getRandom = function(min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH', 'JOHNSON', 'WILLIAMS', 'JONES', 'BROWN', 'DAVIS', 'MILLER', 'WILSON', 'MOORE', 'TAYLOR', 'ANDERSON', 'THOMAS'];

var genLastName = function() {
  var index = Math.round(getRandom(0, lastNames.length - 1));
  return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
  var index = Math.round(getRandom(0, sex.length - 1));
  return sex[index];
};

var Person = function() {
  this.name = genLastName();
  this.age = Math.round(getRandom(0, 100))
  this.sex = "Male"
};

var genPersons = function() {
  for (var i = 0; i < 100000; i++)
    personArray.push(new Person());
};

var changeSex = function() {
  for (var i = 0; i < personArray.length; i++) {
    personArray[i].sex = genSex();
  }
};

var deleteMale = function() {
  for (var i = 0; i < personArray.length; i++) {
    if (personArray[i].sex === "Male") {
      personArray.splice(i, 1)
      i--
    }
  }
};

var t = timer("Array");

var personArray = [];

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personArray.length + " persons.")

Set code:

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

var getRandom = function (min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH','JOHNSON','WILLIAMS','JONES','BROWN','DAVIS','MILLER','WILSON','MOORE','TAYLOR','ANDERSON','THOMAS'];

var genLastName = function() {
    var index = Math.round(getRandom(0, lastNames.length - 1));
    return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
    var index = Math.round(getRandom(0, sex.length - 1));
    return sex[index];
};

var Person = function() {
	this.name = genLastName();
	this.age = Math.round(getRandom(0,100))
	this.sex = "Male"
};

var genPersons = function() {
for (var i = 0; i < 100000; i++)
	personSet.add(new Person());
};

var changeSex = function() {
	for (var key of personSet) {
		key.sex = genSex();
	}
};

var deleteMale = function() {
	for (var key of personSet) {
		if (key.sex === "Male") {
			personSet.delete(key)
		}
	}
};

var t = timer("Set");

var personSet = new Set();

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personSet.size + " persons.")

Answer from snowfrogdev on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › set-vs-array-in-javascript
Set vs Array in JavaScript - GeeksforGeeks
August 5, 2025 - Sets are used to store collections of unique value without allowing duplication. The set is similar to the array and supports both insertion and deletion methods of the array.
Top answer
1 of 7
182

Ok, I have tested adding, iterating and removing elements from both an array and a set. I 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

For this part of the test I 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. This time it would seem that it is exponentially so as it took twice as long during the "small" tests and almost four times longer during the "big" tests.

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.

Conclusions

At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is.

I played around with some hybrid scenarios where an array was created and populated and then converted into a set where some elements would be removed, the set would then be reconverted into an array. Although doing this will give much better performance than removing elements in the array, the additional processing time needed to transfer to and from a set outweighs the gains of populating an array instead of a set. In the end, it is faster to only deal with a set. Still, it is an interesting idea, that if one chooses to use an array as a data collection for some big data that doesn't have duplicates, it could be advantageous performance wise, if there is ever a need to remove many elements in one operation, to convert the array to a set, perform the removal operation, and convert the set back to an array.

Array code:

var timer = function(name) {
  var start = new Date();
  return {
    stop: function() {
      var end = new Date();
      var time = end.getTime() - start.getTime();
      console.log('Timer:', name, 'finished in', time, 'ms');
    }
  }
};

var getRandom = function(min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH', 'JOHNSON', 'WILLIAMS', 'JONES', 'BROWN', 'DAVIS', 'MILLER', 'WILSON', 'MOORE', 'TAYLOR', 'ANDERSON', 'THOMAS'];

var genLastName = function() {
  var index = Math.round(getRandom(0, lastNames.length - 1));
  return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
  var index = Math.round(getRandom(0, sex.length - 1));
  return sex[index];
};

var Person = function() {
  this.name = genLastName();
  this.age = Math.round(getRandom(0, 100))
  this.sex = "Male"
};

var genPersons = function() {
  for (var i = 0; i < 100000; i++)
    personArray.push(new Person());
};

var changeSex = function() {
  for (var i = 0; i < personArray.length; i++) {
    personArray[i].sex = genSex();
  }
};

var deleteMale = function() {
  for (var i = 0; i < personArray.length; i++) {
    if (personArray[i].sex === "Male") {
      personArray.splice(i, 1)
      i--
    }
  }
};

var t = timer("Array");

var personArray = [];

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personArray.length + " persons.")

Set code:

var timer = function(name) {
    var start = new Date();
    return {
        stop: function() {
            var end  = new Date();
            var time = end.getTime() - start.getTime();
            console.log('Timer:', name, 'finished in', time, 'ms');
        }
    }
};

var getRandom = function (min, max) {
  return Math.random() * (max - min) + min;
};

var lastNames = ['SMITH','JOHNSON','WILLIAMS','JONES','BROWN','DAVIS','MILLER','WILSON','MOORE','TAYLOR','ANDERSON','THOMAS'];

var genLastName = function() {
    var index = Math.round(getRandom(0, lastNames.length - 1));
    return lastNames[index];
};

var sex = ["Male", "Female"];

var genSex = function() {
    var index = Math.round(getRandom(0, sex.length - 1));
    return sex[index];
};

var Person = function() {
	this.name = genLastName();
	this.age = Math.round(getRandom(0,100))
	this.sex = "Male"
};

var genPersons = function() {
for (var i = 0; i < 100000; i++)
	personSet.add(new Person());
};

var changeSex = function() {
	for (var key of personSet) {
		key.sex = genSex();
	}
};

var deleteMale = function() {
	for (var key of personSet) {
		if (key.sex === "Male") {
			personSet.delete(key)
		}
	}
};

var t = timer("Set");

var personSet = new Set();

genPersons();

changeSex();

deleteMale();

t.stop();

console.log("Done! There are " + personSet.size + " persons.")

2 of 7
94

OBSERVATIONS:

  • Set operations can be understood as snapshots within the execution stream.
  • We are not before a definitive substitute.
  • The elements of a Set class have no accessible indexes.
  • Set class is an Array class complement, useful in those scenarios where we need to store a collection on which to apply basic addition, Deletion, checking and iteration operations.

I share some test of performance. Try to open your console and copypaste the code below.

Creating an array (125000)

var n = 125000;
var arr = Array.apply( null, Array( n ) ).map( ( x, i ) => i );
console.info( arr.length ); // 125000

1. Locating an Index

We compared the has method of Set with Array indexOf:

Array/indexOf (0.281ms) | Set/has (0.053ms)

// Helpers
var checkArr = ( arr, item ) => arr.indexOf( item ) !== -1;
var checkSet = ( set, item ) => set.has( item );

// Vars
var set, result;

console.time( 'timeTest' );
result = checkArr( arr, 123123 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
checkSet( set, 123123 );
console.timeEnd( 'timeTest' );

2. Adding a new element

We compare the add and push methods of the Set and Array objects respectively:

Array/push (1.612ms) | Set/add (0.006ms)

console.time( 'timeTest' );
arr.push( n + 1 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
set.add( n + 1 );
console.timeEnd( 'timeTest' );

console.info( arr.length ); // 125001
console.info( set.size ); // 125001

3. Deleting an element

When deleting elements, we have to keep in mind that Array and Set do not start under equal conditions. Array does not have a native method, so an external function is necessary.

Array/deleteFromArr (0.356ms) | Set/remove (0.019ms)

var deleteFromArr = ( arr, item ) => {
    var i = arr.indexOf( item );
    i !== -1 && arr.splice( i, 1 );
};

console.time( 'timeTest' );
deleteFromArr( arr, 123123 );
console.timeEnd( 'timeTest' );

set = new Set( arr );

console.time( 'timeTest' );
set.delete( 123123 );
console.timeEnd( 'timeTest' );

Read the full article here

Discussions

When to Use ES6 Sets Instead of Arrays in JavaScript
Advanced Methods: Arrays have set of methods like map, filter, reduce, and sort that are not available on Sets. If you need to transform or aggregate data, arrays are often more convenient. While this was true in the past, it isn't anymore. The Iterator Helpers proposal landed in browsers some time ago, so now you actually do get .map(), .filter(), .reduce() on Sets. Set.prototype.values() & Set.prototype[Symbol.iterator]() will both return an Iterator object that has these methods (along with some other useful methods you can see here ). Around the same time those Iterator methods dropped, Set composition methods like .difference(), .isDisjointFrom(), .intersection(), .union() dropped also. I recommend updating your post to mention these :) As an aside, I was a bit disappointed to read an article titled "When to use Set", but not find any actual examples of real use cases anywhere in said post. So, I'll start you off with an actual use case that goes a teeny bit beyond just removing duplicate values. Whenever you're writing a library that takes user-supplied objects as input, you may run into a use case where you need to decorate that object with a property for book-keeping. For example, suppose your library is some sort of reactive state library, and you need to mark an object as "dirty" after changing some value on it, so that the "reactive" part of your library can inspect that "dirty" flag and decide whether or not to re-render. You could do it like this: function update(obj, fn) { fn(obj); obj.dirty = true; } // ...later on: function render(obj) { if (!obj.dirty) return; performReRender(obj); obj.dirty = false; } OR, you could do it like this: const dirtyObjects = new Set(); function update(obj, fn) { fn(obj); dirtyObjects.add(obj); } // ...later on: function render(obj) { if (!dirtyObjects.has(obj)) return; performReRender(obj); dirtyObjects.delete(obj); } It's not a huge improvement by any means (it may even be a tad slower than the first example), but, it keeps the object clean. In the first example, a user may be surprised to find that the object they provided was mutated without their knowledge/permission (in fact, they could even accidentally override the dirty flag without knowing they are, which is error prone). The second example is practically immune to that problem :) You could actually take that example slightly further. Suppose you have a Directed Acylic Graph (DAG) of dependency relationships, and you wanted to traverse that graph in dependency order, you could use a Set to very easily track which dependencies you have already visited. This is known as a "topological sort": function topologicalSort(values: Value[]) { const sorted: Value[] = []; const visited = new Set>(); function visit(value: Value) { if (visited.has(value)) return; visited.add(value); for (const dependent of value.dependents) { visit(dependent); } sorted.unshift(value); } for (const value of values) { visit(value); } return sorted; } This type of sort is an optimisation that is useful in, you guessed it, reactive state management! Take a framework like Svelte, which allows you to create stores and dependent/derived stores: const num1 = writable(1); const num2 = writable(2); const nums = derived([num1, num2], ([n1, n2]) => [n1, n2]); const doubleNums = derived(nums, (nums) => nums.map(n => n * 2)); If I update num2, I could gaurantee that the update order is num2, followed by nums, followed by doubleNums using said topological sort. EDIT: A topological sort is also useful for detecting infinite cycles and breaking them, which is actually a problem you're very likely to encounter at some point if you're writing any enterprise level code. More on reddit.com
🌐 r/javascript
9
0
June 18, 2025
performance - Why is array.includes an order of magnitude faster than set.has in javascript? - Stack Overflow
Check out jsperf.com/set-array-has-test/3 , I simply changed the size of the array to 100000, and results are wildly different. ... I'll start by stating that I'm not an expert on JavaScript engine implementations and performance optimization; but in general, you should not trust these kind ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Should I use Array or Set if both can be used to finish my task? - Software Engineering Stack Exchange
Note, if you start using an array, and it turns out for further processing a Set would be beneficial (or you need both, the array and the set representation), you can easily convert it: ... I am not a Javascript expert, but I would expect the conversion the other way round to require at a little ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
October 4, 2018
ecmascript 6 - Javascript set vs array vs object definition - Stack Overflow
I'm unclear about what the differences between Set and Array are in Javascript (other than Set is new in ES6). Why would you use Set instead of Array or an Object definition. Why was Set introduced? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Medium
medium.com › @ganeshpant › javascript-set-vs-array-fb515e1cc648
Javascript “Set” Vs “Array”
August 16, 2025 - Set: Ensures that all elements are unique. If you try to add a duplicate element, it won’t be added. Array: when you need to maintain order and allow duplicates.
🌐
Medium
medium.com › web-tech-journals › javascript-set-vs-array-complete-guide-to-set-methods-and-operations-2024-54837f9b4a3c
JavaScript Set vs Array: Complete Guide to Set Methods and Operations [2024] | by Rakesh Kumar | Web Tech Journals | Medium
May 19, 2025 - Web Tech Journals brings you deep dives into frontend architecture, JavaScript, design systems, and emerging tech. Learn, build, and stay ahead of the curve. ... A Set in JavaScript is a built-in object that lets you store unique values of any type.
🌐
Timveletta
timveletta.com › blog › array-set-object-map
Array vs Set vs Object vs Map - Tim Veletta
August 18, 2023 - Consider a list of unique user IDs that gets appended to by some external operation. It would be more efficient to manage this list using a Set rather than an Array since a Set doesn’t allow duplicate items.
🌐
DEV Community
dev.to › david4473 › set-vs-array-14c0
Set vs Array - DEV Community
October 11, 2021 - Set stores data in collections with keys that are iterable in the order of insertion. An array on the other hand - is a global object that stores high-level list-like objects called arrays in the consecutive memory for later use.
🌐
Welby Consulting
welbyconsulting.com › welby consulting › articles › set vs. array in javascript: understanding the differences and use cases
Set vs. Array in JavaScript: Understanding the Differences and Use Cases | Welby Consulting
April 9, 2025 - In summary, sets and arrays are both useful data structures in JavaScript, each with its own advantages and disadvantages. Arrays are ordered and can contain duplicate values, while sets are unordered and contain only unique values.
Find elsewhere
🌐
Medium
medium.com › front-end-weekly › es6-set-vs-array-what-and-when-efc055655e1a
ES6 — Set vs Array — What and when? | by Maya Shavin | Frontend Weekly | Medium
November 9, 2018 - One of the biggest differences here, you may notice, is that elements in Array can be duplicate (unless you tell it not to be), and in Set, they just can’t (regardless what you decide).
Top answer
1 of 4
19
Advanced Methods: Arrays have set of methods like map, filter, reduce, and sort that are not available on Sets. If you need to transform or aggregate data, arrays are often more convenient. While this was true in the past, it isn't anymore. The Iterator Helpers proposal landed in browsers some time ago, so now you actually do get .map(), .filter(), .reduce() on Sets. Set.prototype.values() & Set.prototype[Symbol.iterator]() will both return an Iterator object that has these methods (along with some other useful methods you can see here ). Around the same time those Iterator methods dropped, Set composition methods like .difference(), .isDisjointFrom(), .intersection(), .union() dropped also. I recommend updating your post to mention these :) As an aside, I was a bit disappointed to read an article titled "When to use Set", but not find any actual examples of real use cases anywhere in said post. So, I'll start you off with an actual use case that goes a teeny bit beyond just removing duplicate values. Whenever you're writing a library that takes user-supplied objects as input, you may run into a use case where you need to decorate that object with a property for book-keeping. For example, suppose your library is some sort of reactive state library, and you need to mark an object as "dirty" after changing some value on it, so that the "reactive" part of your library can inspect that "dirty" flag and decide whether or not to re-render. You could do it like this: function update(obj, fn) { fn(obj); obj.dirty = true; } // ...later on: function render(obj) { if (!obj.dirty) return; performReRender(obj); obj.dirty = false; } OR, you could do it like this: const dirtyObjects = new Set(); function update(obj, fn) { fn(obj); dirtyObjects.add(obj); } // ...later on: function render(obj) { if (!dirtyObjects.has(obj)) return; performReRender(obj); dirtyObjects.delete(obj); } It's not a huge improvement by any means (it may even be a tad slower than the first example), but, it keeps the object clean. In the first example, a user may be surprised to find that the object they provided was mutated without their knowledge/permission (in fact, they could even accidentally override the dirty flag without knowing they are, which is error prone). The second example is practically immune to that problem :) You could actually take that example slightly further. Suppose you have a Directed Acylic Graph (DAG) of dependency relationships, and you wanted to traverse that graph in dependency order, you could use a Set to very easily track which dependencies you have already visited. This is known as a "topological sort": function topologicalSort(values: Value[]) { const sorted: Value[] = []; const visited = new Set>(); function visit(value: Value) { if (visited.has(value)) return; visited.add(value); for (const dependent of value.dependents) { visit(dependent); } sorted.unshift(value); } for (const value of values) { visit(value); } return sorted; } This type of sort is an optimisation that is useful in, you guessed it, reactive state management! Take a framework like Svelte, which allows you to create stores and dependent/derived stores: const num1 = writable(1); const num2 = writable(2); const nums = derived([num1, num2], ([n1, n2]) => [n1, n2]); const doubleNums = derived(nums, (nums) => nums.map(n => n * 2)); If I update num2, I could gaurantee that the update order is num2, followed by nums, followed by doubleNums using said topological sort. EDIT: A topological sort is also useful for detecting infinite cycles and breaking them, which is actually a problem you're very likely to encounter at some point if you're writing any enterprise level code.
2 of 4
2
Generally, I start thinking about using Sets when I need to use `.includes` or `.indexOf` or `.splice` on an array I can't guarantee is small or if I am producing a library that wraps one of these operations (and so I can't guarantee how often it gets called). All of these operations are going to scale terribly using an array, while a Set can handle these types of things efficiently, no matter how many values you have in the set. Of course, de-duplication is the key feature that separates the two. Occasionally I find myself de-duping an array using Sets: const uniqueValues = [...new Set(allValues)]; I do this alot in constructors so that the caller doesn't have to concern themselves with duplication, but I need unique values internally for the class. This is not going to be the most efficient way to do this, typically, but it is very clean and simple. If the number of values is small and the code path isn't super hot, it should not be a concern.
🌐
LinkedIn
linkedin.com › pulse › array-vs-set-javascript-manvendra-singh-scjbf
Array vs Set in JavaScript
November 25, 2023 - Performance:Sets may have better performance for certain operations (e.g., checking for existence) due to their unique property. Order:Arrays maintain order, and elements can be accessed using indexes.
Top answer
1 of 2
6

The use of either Array or Set by your function is equivalent: You create a container, and you push stuff into it. This leaves two areas for consideration:

  1. What does the consumer need to do with the container?

  2. Which container is more efficient (space or time)?

If you find that the consumer just iterates over the container, both Array and Set are equivalent again from this usage perspective. However, if your user needs to answer the question "is this index in the container?", then Set is the only appropriate container type.

Once you have asserted that the container type is indeed irrelevant to use, both on the producer and consumer side, go for the more efficient container:

  • Array should be implemented as a simple slap of contiguous memory that holds (the references to) its elements. A push() generally means 1) checking for space (one comparison), 2) appending the new element to the end of the buffer, and 3) updating the length field.

  • Set is required to ensure that its elements are unique. That is, where Array.push() is happy to push an element twice, Set.insert() must somehow catch this condition and handle it. This requires extra work. To get O(1) performance, Set would normally be implemented as a hash table. Hash tables are fast, but they are definitely more complex than a simple, contiguous buffer. Thus, Set.insert() will generally have to do significantly more work than Array.push(), and its data structures are very likely to consume more memory.

Both space and time efficiency are better for Array than for Set. And this is why I would default to using Array over Set whenever their use is equivalent.

2 of 2
2

From what you have shown in your question, it does not matter (and consider to refactor your code in case it starts to matter).

not limited to this case, if I found both Array and Set can finish my task, should I use Array or Set

Producing an Array or a Set is typically not an end in itself, it is a means to an end, so often you can find out what the caller of your method which produces this result might prefer.

Note, if you start using an array, and it turns out for further processing a Set would be beneficial (or you need both, the array and the set representation), you can easily convert it:

  let resultSet = new Set(results)

I am not a Javascript expert, but I would expect the conversion the other way round to require at a little bit more code. Thus, if in doubt, I personally would start with an array first, and switch to a set if it fits better, but that is somewhat opinionated.

🌐
Medium
oluwadaprof.medium.com › sets-vs-arrays-in-javascript-0ccbca1c08a1
Sets vs Arrays in JavaScript. JavaScript gives us multiple ways to… | by Israel | Medium
January 29, 2026 - const users = new Set(['Alice', 'Bob', 'Alice']); console.log(users); // Set { 'Alice', 'Bob' } ... Order preserved → (✅ Array) (✅Set) Allows duplicates → (✅Array) (❌Set) Index access → (✅Array) (❌Set) Lookup performance → O(n)Array O(1)Set Built-in uniqueness → (❌Array) (✅Set) Serializable (JSON) → (✅Array) (❌Set)
🌐
Better Programming
betterprogramming.pub › javascript-sets-vs-arrays-25337bea7939
JavaScript: Sets vs. Arrays. Introducing Sets, the ES6 data type you… | by Chris Geelhoed | Better Programming
November 18, 2019 - const characters = new Set(['Rod', 'Todd', 'Sherri', 'Terri']) Arrays are a major building block in most JavaScript applications, both old and new. If you have written JavaScript before, you are probably already familiar with them.
🌐
Rune Hub
rune.codes › home › tutorials › javascript › set vs array in javascript: complete guide
Set vs Array in JavaScript: Which to Use and When | Rune Hub
July 15, 2026 - Set is for uniqueness and fast membership checks. Array is for ordered lists, indexed access, and sequence manipulation. Convert between them freely and choose based on what your data needs: uniqueness or position.
🌐
Medium
medium.com › front-end-weekly › practical-difference-between-array-and-set-in-javascript-56df75d1ebfa
Practical Difference between Array and Set in Javascript | by Frontend Master | Frontend Weekly | Medium
December 6, 2023 - Javascript Development · Web Development · Frontend Master · 3 min read · ·Nov 29, 2023 · -- Listen · Share · Press enter or click to view image in full size · -Array: - Maintains the order of elements based on their indices.
Top answer
1 of 2
34

Every value in a set has to be unique, but in Array you can push same value as many times as you'd like.

"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

Removing values, interestingly enough, when dealing with small amounts of data, there isn't much performance difference between the two (Array and Set), but when you start to deal with big data, removal is a lot faster in Sets vs Arrays.

Adding values to Array is 4 times faster than adding them to set.

Iterating through the values Array is here also better performer (Growing exponentially based on the amount of data).

You can read more about the performance differences at; Javascript Set vs. Array performance

"At 10k elements, both tests ran comparable times (array: 16.6 ms, set: 20.7 ms) but when dealing with 100k elements, the set was the clear winner (array: 1974.8 ms, set: 83.6 ms) but only because of the removing operation. Otherwise the array was faster. I couldn't say exactly why that is."

Count unique items in object Set Vs Object write-up https://github.com/anvaka/set-vs-object

TL:DR Set is almost two times faster than Object.

Why Set was introduced (My guess)?

There are sometimes when you need an easy way to build up a collection of values and you have to make sure each value is unique. This brings a lot overhead away from the old fashioned check if array has the value or not and then push or skip.

This scenario was not covered in the performance post I linked earlier, but doing fast experiment on Array of 10,000 items and then adding 15 items where 5 were duplicates to the combined collection, adding to array with checking for duplicate values and skipping if duplicate it took 74ms and with set just using the set.add(value) it took 9ms.

When would you need this?

One real life example that came to my mind is that if you have an email marketing letter and you for example would have options; - TV - Music - Movies - Sports

One day your client or you would like to have only one email option for TV, Music and Movies called "Entertainment". You would need to build up a new collection based on the data from these 3 different values and you would need to make sure each email are added to the new entertainment emailing list only once. Meaning that users could've opted-in for Movies as well as TV if they are interested in both.

Here you could just make set Entertainment and then iterate through all the lists TV/Music/Movies and use Entertainment.add(email) and the set would take care of skipping values that already exists in the list. Hence avoiding duplicate emails in the emailing list.

Also set would be optimal format to store your email subscriber addresses, as nobody could accidentally opt-in twice for you emails.

2 of 2
0

Basically, set is used to store elements uniquely whereas in arrays, you can duplicate the elements. And regarding objects, in use cases when you also need to store additional information regarding each element, then you would choose object over set and array.

For example: storing info. of your apps users, which include their name, phone no., address, email etc. Then in objects, you can define a key, let's say email (or you could also create a unique id), then keys in your object would be email (or the other one) and the additional info about the user would get stored as properties.

🌐
Frontend Masters
frontendmasters.com › courses › blazingly-fast-js › optimizing-code-sets-vs-array
Optimizing Code: Sets vs Array - Blazingly Fast JavaScript | Frontend Masters
ThePrimeagen discusses the performance of using sets versus arrays in JavaScript and analyzes a code example that compares the speed of finding unique characters using sets and arrays. They …
🌐
Medium
oieduardorabelo.medium.com › javascript-set-vs-array-quando-e-como-usar-cf05a7a6ce54
JavaScript: Set vs Array, quando e como usar? | by Eduardo Rabelo | Medium
July 10, 2019 - Uma das maiores diferenças aqui, você pode perceber, é que os elementos no Array podem ser duplicados (a menos que você diga que não deve ser), e no Set, eles simplesmente não podem ser (independentemente do que você decidir).