ES6 — Set vs Array — What and when?

Maya Shavin
Jan 24, 2018 · 6 min read
Image for post
Image for post
Set VS Array

What is Set and what is Array?

Everyone who works with JS until now is familiar with (don’t tell me you don’t). But what exactly is ?

Well, in general, is type of structure representing(numbers, objects, etc…)

Example: [1,2,3,2]

How about Set?

, more familiar as a Math concept, is an which contains elements/objects the need of being allocated orderly by index.

Example: {1,2,3}

Yup, by definition, Array and Set are technically different concepts.

One of the biggest differences here, you may notice, is that (unless you tell it not to be), and(regardless what you decide).

In addition, is considered as “” type of data structure, while is considered as “”.

A quick reminder for those who don’t remember,

are collections of data which are ordered by an index value

are collections which use keys; these contain elements which are iterable in the order of insertion.

Easy right? Now one may wonder, if they are different, why we bother compare between them?

In programming world, taken same data set (no duplicates), we can either use Array or Set to be our chosen structure to store this data set. However, depending on the use case, — and we want to achieve that. And in order to understand which to choose, we need understand firstly who they are, how they are built and what they are capable of. Since we have done with “who they are”, let’s move on to “how to build one” in JS.

Constructing

Array

Array is very straight-forward. To declare new array in JS, you can either use normal literal directly:

var arr = []; //Empty array
var arr = [1,2,3]; //Array which contains 1,2,3

Or use built-in constructor

var arr = new Array(); //empty array
var arr = new Array(1,2,3);//Array which contains 1,2,3

Or even cooler:

var arr = Array.from("123"); //["1","2","3"]

Just one piece of advice — unless you really really really need to, since:

  • It performs much slower than the normal [] literal. (this will be explained in a different article — maybe ;)).
  • [] saves more typing time (try it :))
  • You may end up making some classical mistakes such as:
var arr1 = new Array(10); //arr1[0] = undefined but arr1.length = 10
var arr2 = [10]; // arr2[0] = 10 and arr2.length = 1;
var arr3 = new Array(1,2,3); //[1,2,3]
var arr4 = [1,2,3];//[1,2,3]

So #1 thumb rule — keep it simple!

Set

Set has built-in constructor. Yup, there is no short-cut as in array.

Set([iterable])

In order to create new set, we have to use syntax, for example:

var emptySet = new Set(); 
var exampleSet = new Set([1,2,3]);

But definitely not:

new Set(1);

Set receives object as its input parameter, and will create set object respectively. Hence, we can construct a set from an array — but it will only include distinct elements from that array, aka no duplicate.

And of course, we can also convert a set back to array using method.

var set = new Set([1,2,3]); // {1,2,3}
var arr = Array.from(set);//[1,2,3]

OK, now that we know how to create them, what about their capabilities? Let’s do a small comparison between the most basic methods Array/Set provides, which are:

Locating an element / Accessing an element

  • First of all, like in Array, which means:
console.log(set[0]); //undefined
console.log(arr[0]); //1
  • More important, because the Array data is stored in consecutive memory, the CPU will be able to access the data much faster due to pre-fetching. Hence in generalcompared to other type of abstract data types.
  • Checking if an element is in Set has simpler syntax than Array by using VS
console.log(set.has(0)); // boolean - false
console.log(arr.indexOf(0)); // -1
console.log(set.has(1)); //true
console.log(arr.indexOf(1)); //0

Which means in Array, we need to ask an extra check if we want to make a condition where the element is in Array:

var isExist = arr.indexOf(1) !== -1;

: ES6 does provide which behaves similarly to (), however, it is not supported widely — aka not in IE yet (surprise :)!).

Add/Insert new element

  • Adding new element to Array can be done quickly in by using — element will be added to the end of the array.
arr.push(4); //[1,2,3,4]
  • Or it can also be done in by using — add element to the beginning of array — with n is the length of current array.
arr.unshift(3); //[3,1,2,3]
arr.unshift(5, 6); //[5,6,3,1,2,3]
  • In , there is only one way to add new element — . Because Set has to maintain the “” property between its set members, in each time calling , Set needs to check through all members to make sure no duplicate before continuing. Generally will take running time. However, thanks to , add() in Set will likely take only
set.add(3); //{1,2,3} 
set.add(4); //{1,2,3,4}

Hence here Set performs almost the same with Array in adding element. How about removing?

Remove element

  • One of the nice things that make Array so popular is because it provides a lot of different methods to remove an element, for example:

— removes and returns the element. This takes .

arr.pop();//return 4, [5,6,1,2,3]

— removes and return element. This takes .

arr.shift(); //return 5; [6,1,2,3]

— remove a This can take up to O(n).

arr.splice(0,1); //[1,2,3]
  • Meanwhile, in Set, we will use

— remove a from Set.

set.delete(4); //{1,2,3}

— remove from Set.

set.clear(); //{}
  • While Array to remove a specific given element (except if we know its index), we will need the help of an extra external function to look for that element’s index and perform splice(), Set has simple and easy to use.

In addition, Array does provide us a lot more native functionalities (reduce(), reverse(), sort(), etc…), compared to Set which currently only have the most basic functionalities mentioned above. So, some of you may think, why would we ever prefer Set over Array at all?

So, when is Set better? And when is Array better?

  • Firstly, Set is different than Array. It is not meant to replace Array entirely, but to provide additional support type to complete what Array is missing.
  • Since Set only contains distinct elements, it makes life much easier if we know in advance we want to avoid saving duplicate data to our structure.
  • Basic operations of Set like , etc… are easily implemented effectively based on the native built-in operations provided. Due to the delete() method, it makes intersect/union between 2 Sets much more comfortable than doing the same to 2 Arrays.
  • Array is meant for scenarios when we want to keep elements ordered for quick access, or do heavy modification (removing and adding elements) or any action required direct index access to elements (for example, try doing Binary Search on Set instead of Array — how do you access the middle located element?)

Conclusion

In general, to my opinion, doesn’t really have a huge clear advantage over , except in specific scenarios such as when we want to maintain “distinct” data with minimum effort, or to work with a lot of distinct data sets together using the most basic set operations, without the need of direct accessing element.

Otherwise, should always the choice. Reason? Less CPU work to fetch the element when it is needed.

Do you agree? Feel free to discuss ;).

P.S — Corrected the running time for since in general is implemented optimally using Hash table approach. Thanks @André Patrício for pointing this out 😃


Frontend Weekly

It's really hard to keep up with all the front-end…

Maya Shavin

Written by

Senior Front-End Developer @Cloudinary www.mayashavin.com

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Maya Shavin

Written by

Senior Front-End Developer @Cloudinary www.mayashavin.com

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store