Set vs Array
Published: 2021-10-11 07:13:52


There are several ways you can solve coding problems as a JavaScript developer, thanks to the plethora of pre-established data structures designed to solve simple to real-world problems. 

Data structures are techniques for storing and organizing data, which enables efficient modification. The data structure also determines relationships between data and functions to use in accessing them.

JavaScript data structures have their respective use-cases; this is due to the unique properties each object possess. However, this doesn't mean there isn't any form of similarities between them. The Array and Set data structure types have a lot in common, and we're going to be looking at what similarities they share, how they differ from each other and their use-cases.
***
##What is a Set and an Array?

###Set

Set is a data type that stores data that are unique values of any type, whether primitive or object references. Set stores data in collections with keys that are iterable in the order of insertion.

###Array

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. Every array has several cells, and each cell has a numeric index that is used to access its data. It is the most basic and most used of all data structures.

Now that we know what they are, let's take a look at the similarities between these objects.
***
##Similarities & Differences

For us to comprehend some of the technical aspects of this section, we need to understand how to construct or initialize either of the objects.

Both objects have a built-in constructor which utilises the `new` syntax for declaring a new data structure. However, unlike a set, an array is not limited to this method of declaration. An array can also be declared with the literal method.

You can initialize a new Set like this:

```javascript

const set = new Set();

```

And a new array like this:

```javascript

const arr = new Array();

```
Or:

```javascript

const arr = [];

```
In addition, the literal method of initialising an array is much faster; construction-wise, and even performance-wise. The constructor method, however - is slower compared to the former, and prone to mistakes such as this: 

```javascript

const arr = new Array(20);

arr[0]  //outputs: undefined

arr.length //outputs: 10

//Literal method
const arrLtr = [20];

arrLtr[0] //outputs: 20

arrLtr.length //outputs: 1

//The later is accurate
```

With that out of the way, we can now go into the nitty-gritty of what these objects have in common.

The similarities between Set and Array is conspicuous. if you've ever worked with arrays before (who hasn't anyway), you'll immediately notice some of the things they have in common. But even with the glaring dead ringer, the differences between them are quite stretched.

One of the biggest, perhaps the biggest, differences between Set and Array is that; Set can only contain one instance of a value. For example, in an array of `people`, a `peter` value can appear as many times as you want. Whereas in Set, you can only have one `peter` value. If you try to add more, nothing happens.

What if you hard-code duplicate values into a set, what happens?
Set will only pick one of the duplicate values and delete the rest.
However, Set's intolerance for duplicate data values has its perks, especially in cases where you don't want duplicate values or data leaks in your data structure.

Most of Set and Array's likeness lies within how they operate; how they populate their structure with data and otherwise.
***
##Inserting and removing elements

Each object has its built-in methods for adding and removing values from its respective structure. While Array has more than one method of inserting or removing values, Set only has one. 

Before going deep into this section, we first need to understand how items are inserted and removed from a data structure.

A Data structure is basically a stack of objects that are inserted and removed according to the last-in-first-out principle, which is also known as (LIFO).
Elements can only be added and removed from the top of the stack. A helpful analogy is to think of a stack of books; you can add new books from the top and remove only the book at the top.

<img width="100%" style="width:100%" src="https://media.giphy.com/media/tC5t2np7BZK5WI3G3O/source.gif">

###Inserting and removing elements in an Array

The Array has two methods for this functionality `push()` and `pop()`. The push method adds new items to the top of the data structure, while pop removes items from the top of the structure i.e the last item added. 

####Array.protoype.push()

```javascript

const arr = [ ];
arr.push("Mario")

console.log(arr);
//Output:
// Mario

```

####Array.protoype.pop()

```javascript
const arr = ["Mario", "Luigi", "Bowser"]
//Remove "Bowser" 
arr.pop()

console.log(arr)

//Output:
// Mario, Luigi

```

####Array.protoype.unshift() / shift()

The `unshift()` and `shift()` methods works contrary to the LIFO principle, these methods are used to insert and remove items to the bottom of a data structure i.e at index `0`.

####Array.protoype.unshift()

```javascript

const arr = [ 4, 6, 8, 10 ];

//Add 2 to index 0
arr.unshift(2)

console.log(arr)

//Output:
// 2, 4, 6, 8, 10
```
####Array.protoype.shift()

```javascript

const arr = [ 2, 4, 6, 8, 10 ];

//Remove 2 from index 0
arr.shift()

console.log(arr)

//Output:
// 4, 6, 8, 10

```

####Array.protoype.splice()

`splice()` is another array method that can be used to remove or replace an existing element in an array. The method takes in two parameters for deleting an element and three for replacing or adding a new element: 

```javascript
splice(start, deleteCount)
```
Or

```javascript
splice(start, deleteCount, item1)
```

`start`
The index at which you want to start inserting or delete elements from an array.

`deleteCount`
An integer specifying the number of elements to be removed from the `start` index. N.B This is an optional parameter.

`item`
This is the element to be added to an array from the `start` index. This is also an optional parameter.

Here is a basic `splice()` demo:

**Remove 0 (zero) elements before index 2, and insert "John".**

```javascript
let students = ['Hugh', 'Jack', 'Dave', 'Katerina']; 
students.splice(2, 0, 'John');

console.log(student);

//Output:
//['Hugh', 'Jack', 'john' , 'Dave', 'Katerina']
```

**Remove 1 element at index 1**

```javascript
let students = ['Hugh', 'Jack', 'Dave', 'Katerina']; 
let removedStudents = students.splice(1, 1);

console.log("Students:" + students);
console.log("Removed students:" + removedStudents);

//Output:
//Students: ['Hugh', 'Jack', 'john' , 'Dave', 'Katerina']
//Removed students: [ 'jack' ]
```

`splice()` can also be used to instantly clear every element in an array like this:

```javascript
  let fruits = ['Mangos', 'papaya', 'Apple'];

  fruits.splice(0, fruits.length);

  console.log(fruits);

  //Output:
  // [ ] Empty array
```

For a more in-depth analysis on `splice()`, [Visit the Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).

####Array.from()

The `from()` method lets you populate an array with an array-like or iterable object. That is; an object with a length property and iterable objects such as a `set`. In a nutshell, you can populate an array with elements in a pre-existing `set`.

```javascript
   let fruits = new Set(['Mangos', 'papaya', 'Apple']);

   let arr = Array.from(fruits);

   console.log(arr);  

  //Output:
  // [ 'Mangos', 'papaya', 'Apple' ]
```

###Inserting and removing items in a Set
Just as stated above, Set has only one method of adding items to its structure; using the `add()` method. This method works just like Array's `push()` method. It also has a `delete()` method for removing items just like the `pop()` method. 
Set follows the LIFO principle of inserting and removing elements in a data structure, but unlike Array, Set doesn't have a way around the LIFO principle; elements can only be inserted and removed from the top of a set data structure.

####set.prototype.add()

```javascript

const set = new Set();

set.add("Peach");
set.add("Mario");

console.log(set)

//Output:
// "Peach", "Mario"

```

####set.prototype.delete()

```javascript

const set = new Set(["Peach", "Mario", "Bowser"]);

set.delete("Bowser");

console.log(set);

//Output:
// "Peach", "Mario" 
```

Similarly to Array's `from()` method, Set can also populate its structure with a pre-existing array. Set doesn't require an extra method for this functionality, the constructor handles it just fine:

```javascript
   let arr = ['John', 'Mike', 'Steph'];

   let newSet = new Set(arr);

   console.log(newSet);

  // Output:
  // { 'John', 'Mike', 'Steph' }
```
####set.prototype.clear()
Set's `clear()` method is a very straightforward and efficient method for clearing out elements in a data structure. It doesn't require extra arguments like the former's method.

```javascript
   let newSet = new Set([ 'John', 'Mike', 'Steph' ]);
   newSet.clear();

   console.log(newSet);

  // Output:
  // { } Empty set object
```
***
##Accessing elements 

How elements in a data structure are accessed or selected is determined by the data type being used. Take an Array, for example, elements in an array are accessed by their cell's numeric index. This means, the first element in an array can be accessed at index 0, and the last element; at the index value equal to the array's length minus 1.

**Accessing the first element**

```javascript
  let arr = [ 'cat', 'dog', 'mouse' ];
  console.log(arr[0]);

  //This will output 'cat'
  //Because the 'cat' value is at index 0
  
```

**Accessing the last element**

```javascript
  let arr = [ 'cat', 'dog', 'mouse' ];
  console.log(arr[ arr.length -1]);

  //This will output 'mouse'
  //Because the 'mouse' element is the last in the array
  
```

Set accesses elements in a data structure differently. This is because a set does not support the selection of random elements by its index like Array. So the `indexOf()` method will only work with an array.

```javascript
  let arr = [ 'cat', 'dog', 'mouse' ];
  let newSet = new Set(arr);

  console.log(arr[0]) // outputs 'cat'
  console.log(newSet[0]) // outputs undefined
```
Set checks if an element is in its structure with the `has()` method. This method is simpler compared to Array's technique for checking elements.

```javascript
  let animalSet = ([ 'cat', 'dog', 'mouse' ]);
  let isMouse = animalSet.has('mouse')

  console.log(isMouse) // outputs true
```
Performing something similar in an array requires an extra conditional check and code with the `indexOf()` method like this:

```javascript
  let arr = [ 'Peach', 'Mario', 'Bowser' ];

  //checks if Mario is at index 1
  let isMario = arr.indexOf('Mario') === 1;

  console.log(isMario) // outputs true
```

The `indexOf()` method returns  `-1` if the element being searched for is not present in the structure.
***
##Length and size

Certain functionalities require we check the total amount of elements present in an array or set structure. Javascript has a global `length` property for displaying the number of characters in a string and elements in any data type that stores list-like elements. 
And If there's anything to go by, it's that an array works with almost every global method and property in Javascript. So without dwelling too much on it, here's a demo of the `length` property in an array:

```javascript
const arr = [2, 3, 4];

console.log(arr.length)

//Outputs
// 3
```

Set has its unique method for checking the number of elements in a set; with the `size` method. This method works exactly like the length property:

```javascript
const set = new Set();

set.add(2)
set.add(3)
set.add(4)

console.log(set.size)

//Outputs
// 3
```
***
##Iteration

There are different ways one could iterate over elements in an array or set, but unlike the former; set isn't compatible with the conventional techniques for iterating over elements in programming using functions like the `for` and `while` loop statements.

Looping in a set can be easily done with the `forEach()` method. Although several other methods can be used in its stead, methods like:

- iterator()
- values()
- entries()...

The `forEach()` method is perhaps the most unequivocal of them all.

```javascript
const breeds = new Set();

breeds.add("dog")
breeds.add("cat")
breeds.add("bunny")

const iterate = (value) => {
  console.log(value + " breed" ); 
}

breeds.forEach(iterate);

//Outputs:
// dog breed
// cat breed
// bunny breed
```

When it comes to iteration, an array has a list of flexible options to choose from, your choice is often determined by the kind of functionality you're trying to implement. We can't go deeply into every one of these methods as they are beyond the scope of this article, but we'll examine the most used of them all; the `for` and `while` loop.

####For loop

```javascript

const arr = [ 1, 2, 3, ]

for (var i = 0; i < arr.length; i++) {
  console.log('number: ' + arr[i]);
}

//Output:
// number: 1
// number: 2
// number: 3

```
####While loop

```javascript

let x = 0;

while (x < 5) {
  x++;
}

console.log(x);

//Output:
// 5

```

Visit the [Mozilla docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) to learn more about these statements.
***
##When to use Set or Array

Knowing when to use a set or an array is a no-brainer, it generally boils down to two things; unique elements and Performance.

- Use set when you want unique elements in your data structure. Although an array can be modified to accept unique elements, set is, however, optimized for such functionalities out of the box.

- If you want high-performance element lookups use set's `has()` method. 

- If you want an easy access of elements, easy element swapping and binary search of elements ( i.e accessing elements located in any part of a data structure; front, middle and back ), an array is your best bet.

- If you want to prevent memory leaks in your data structure, use a set.

- If you want flexibility and more feature, use an array.
***
##Conclusion

One thing to note is that both objects shine within their range of specialities, even though the array has the efficacy of becoming the Swiss army knife of data structure; set's high-performance methods and intolerance for duplicates makes it stand out.

Your decision on which to use will be highly influenced by the nature of the project you're working on. It's not really about which is better, but which is right for the job.