Guide to JavaScript data structures (arrays, sets, maps)
Tags: javascript, webdev, beginners, learning
Published: 2020-03-06 15:22:26

---
title: Guide to JavaScript data structures (arrays, sets, maps)
published: true
description: 
tags: javascript, webdev, beginners, learning
cover_image: https://cdn.pixabay.com/photo/2016/01/19/16/49/laptop-1149412_1280.jpg
---

Hello! Data structures stand for one of the most valuable skills for every software engineer. Last year, I already published a comprehensive guide to Java collections. This time, I would like to provide this post on built-in data structures in JavaScript. They include classical arrays, as well two new data structures - Maps and Sets - that were introduced in ES6. This post overviews most important operations for arrays, maps and sets in vanila JS, including declaration, addition/deletion of elements, iterations, access elements, get a size of collection or validation of an existence of element in collection.

## Array

Arrays are oldest JS collections. From a technical point of view, an array stands for a data structure that stores a sequence of elements. In Javascript, arrays are __objects__. However, compare to [Java](https://andreevi.ch/custom-update-queries-with-reactive-mongodb-for-spring) arrays, JS does not fix neither size of arrays neither type of objects. Elements are accessed using their index, which is [0; length of array - 1]. This section overviews most important arrays operations.

### Declaration

To declare an array in JS there two general ways:

* Using _array literal_ syntax
* Using a constructor of an __Array__ class

This code snippet demonstrates how to create arrays with these approaches:

```js
// using array literal

let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];

// using constructor

let numbers = new Array(1,2,3,4,5);

```

### Add elements

JS makes a difference with addition/deletion of elements, depending of their position in array (front/end). That means, that in order to [insert a new element](https://andreevi.ch/custom-update-queries-with-reactive-mongodb-for-spring/#add-to-a-nested-array) to __the end__ we use __push__ method, while __unshift__ operation adds element to __1st position__. Take on look on the following example:

```js
let numbers = new Array(1,2,3,4,5);
console.log(numbers); // [1,2,3,4,5]

numbers.push(6);
console.log(numbers); // [1,2,3,4,5,6]

numbers.unshift(7);
console.log(numbers); // [7,1,2,3,4,5,6]
```

Also, both methods can take __multiple__ arguments at once:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
names.push('Gabriela', 'Hana', 'Katarina');
```

### Remove elements

As with addition, there are several ways to remove elements from JS array:

1. From the beginning using __shift__
2. From the end using __pop__
3. Using __filter__ operation

Let observe first two operations in this example:

```js
let numbers = [1,2,3,4,5,6,7];

numbers.shift();
console.log(numbers); // [2,3,4,5,6,7]

numbers.pop();
console.log(numbers); //[2,3,4,5,6]
```

Another approach to remove elements from array is by using __filter__. Contrary to previous two operations, this approach __creates a new array__, with elements, filtered using given condition (predicate). Take a look on this code, that creates of an array with even numbers:

```js
let numbers = [2, 15, 6, 19, 54, 12, 9];

let even = numbers.filter(value => {
	return value %2 === 0
});

console.log(even); //[2,6,54,12]
```

### Access an element

Elements of array are accessed using an _index_, that has value of [0; array length - 1]. This code snippet demonstrates how how to do it:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let name = names[0];
console.log(name); //Anna
```

### Check for presence

There are several ways to [check an existance](https://andreevi.ch/custom-update-queries-with-reactive-mongodb-for-spring/#query-by-a-nested-objects-field) of the element in the array:

* Using __includes__ method: return boolean value on presence/absence
* Using __indexOf__ that returns an index of the element of -1 if it is not present. __NB__ used mainly for targeting old browsers
* Using __every__ and __some__: both checks elements for satisfying a predicate (condition) and returns a boolean result if all elements/some elements are valid for condition

Take a look on this example:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let hasName = names.includes('Carolina');
console.log(hasName); // true

let cities = new Array('Madrid', 'Prague', 'Buenos Aires', 'Brussels');
let paris = names.indexOf('Paris');
console.log(paris); // -1

// using every and some
let numbers = [2, 15, 6, 19, 54, 12, 9];

let everyIsEven = numbers.every(value => {
	return value%2===0
});
console.log(everyIsEven); // false

let someAreEven = numbers.some(value => {
	return value%2===0
});
console.log(someAreEven); // true
```

### Get size

The array's size in JS is a _property_, not a function. To get it, call __Array.length__:

```js
let numbers = [2, 15, 6, 19, 54, 12, 9];
console.log(numbers.length); // 7
```

In JS it is possible also to __set a size of an array__ by assigning a new value to __length__:
```js
let numbers = [1,2,3,4,5];
console.log(numbers.length); // 5

numbers.length = 3;
console.log(numbers); // [1,2,3]
```

### Iterations

To loop over elements of array use __forEach__ method. This code snippet demonstrates an usage of this method:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
names.forEach(name => console.log(name)); 
```

This will iterate over the array __names__ and print each value.

## Set

Sets in JS were introduced in ES6. In computer science, set is a collection that contain no duplicate elements. JS sets can store any type of elements - either objects or primitives (string, number, bigint, boolean, null, undefined, and symbol).

### Declaration

JS permits to create an empty set or a set from an array using constructor. Take a look on the code snippet below:

```js
// empty set
let set = new Set();

// from array
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let nameSet = new Set(names);
```

### Add elements

To insert new elements in set use __add__ method. It returns a set, so it is possible _to chain_ several add methods. Here is an example:

```js
let numbers = new Set();

numbers.add(1);
numbers.add(2).add(3); // chain

numbers.add(2); //2 already in array
```

Sets also can store values of different types as well __undefined__, __NaN__ and __null__ values:

```js
let set = new Set();
set.add(1).add('Hello world').add(NaN).add(undefined);
console.log(set); //Set(4) [ 1, "Hello world", NaN, undefined ]
```

### Remove elements

Set provides __delete__ method that removes a value from collection and returns a boolean value - _true_ if element was successfully removed, and _false_ if element was not removed (or not presented initially):

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let nameSet = new Set(names);

nameSet.delete('Carolina'); 
console.log(nameSet); // Set(4) [ "Anna", "Barbora", "Denisa", "Eva" ]

let result = nameSet.delete('Marketa');
console.log(result); // false
```

There is also method __clear__ that remove __all__ elements in set:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let nameSet = new Set(names);

console.log(nameSet); // Set(5) [ "Anna", "Barbora", "Carolina", "Denisa", "Eva" ]

nameSet.clear();

console.log(nameSet); // Set []
```

### Check for presence

In order to check an existance of an element in sets, use __has__ method. It returns _true_ if the item is in the set, and _false_ if it isn't. Take a look on the following code snippet:

```js
let names = ['Anna', 'Barbora', 'Carolina', 'Denisa', 'Eva'];
let nameSet = new Set(names);
let has = nameSet.has('Anna');
console.log(has); // true
```

### Iterations

There are two approaches to loop over set's elements:

* Using __forEach__
* Using __of__

Here, both snippets iterate over elements and print each of them:

```js
let nameSet = new Set(['Anna', 'Barbora', 'Carolina']);

// using forEach
nameSet.forEach(name => console.log(name));

// using of
for (name of nameSet) {
	console.log(name);
}
```

## Map

Final data structure is _map_. Technically, maps are data structures, that store elements in a key-value format. Like sets, maps were also introduced in ES6. So, in JS map is an object which holds key-value pairs and remembers the original insertion order of the keys. Both keys and values can be primitive values or objects (including NaN, null or undefined values), however keys should __be unique__, e.g. no duplicates.

### Declaration

Same as sets, maps can be created in two ways:

* An empty map with __Map()__ constructor
* From iterable collection

Here is an example that demonstrates how to initialize maps:

```js
let emptyMap = new Map();

let phoneNumbers = new Map([['5352342', 'Anna'], ['9358432', 'Barbora'], ['9874342', 'Carolina']]);
```

__NB__ that in the second approach we passed an array of arrays in form of __[[key, value], [key, value] ...]__.

### Add elements

Map permits to insert new elements using __set__ method that accepts two arguments: key and value. If key already presents in the map, its value would updated with a new value:

```js
let words = new Map();

words.set('apple', 'manzana');
words.set('orange', 'naranja');
words.set('pineapple', 'pina');

// update an existing key
words.set('pineapple', 'piña');
```

Like with sets, it is also possible to chain multiple __set__ methods together.

### Remove elements

There are two ways to remove elements from JS map:

* By provided key using __delete__ method
* Remove __all__ elements with __clear__ method

Take a look on the following code snippet below:

```js
let phoneNumbers = new Map([['5352342', 'Anna'], ['9358432', 'Barbora'], ['9874342', 'Carolina']]);
console.log(phoneNumbers); // Map(3) { 5352342 → "Anna", 9358432 → "Barbora", 9874342 → "Carolina" }

phoneNumbers.delete('5352342');
console.log(phoneNumbers); // Map(2) { 9358432 → "Barbora", 9874342 → "Carolina" }

phoneNumbers.clear();
console.log(phoneNumbers); // Map (0)
```

### Access an element

Maps allow to retrieve a _value_ for a given _key_ using __get__ method. If element is not presented in map, method will return __undefined__:

```js
let words = new Map();

words.set('apple', 'manzana');
words.set('orange', 'naranja');
words.set('pineapple', 'pina');

let word = words.get('apple');
console.log(word); // manzana

word = words.get('hello');
console.log(word); // undefined
```

### Check for presence

In order to check if map contans a element (value) for a specified key use __has__:

```js
let phoneNumbers = new Map([['5352342', 'Anna'], ['9358432', 'Barbora'], ['9874342', 'Carolina']]);

console.log(phoneNumbers.has('5352342')); // true
```

### Iterations

Last thing about maps is iteration. There are several ways to achieve this task:

* Loop over values using __values__
* Loop over keys using __keys__
* Loop over key-value pairs using __entries__

Take a look on code examples:

```js
// create map
let map = new Map();
map.set(4211234, 'Anna').set(2447759, 'Barbora').set(3333123, 'Carolina').set(4444095, 'Denisa');

// iterate over keys
for (key of map.keys()) {
	console.log(key)
}

// iterate over values
for (value of map.values()) {
	console.log(value)
}

// iterate over pairs
for ([key, value] of map.entries()) {
	console.log(key + ': ' +value)
}
```

## Conclusion

In this post we observed three built-in data structures in JS - arrays, sets and maps. We checked most important operations on these collections, including declaration, addition/deletion of elements, iterations, access elements, get a size of collection or validation of an existence of element in collection.

## References

* Clifford A. Shaffer _Data Structures & Algorithm Analysis_ 3 edn, Dover Publications, 2013
* Glad Chinda _Hacks for Creating JavaScript Arrays_ (2018) Freecodecamp, [read here](https://www.freecodecamp.org/news/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b/)
* Jordan Irabor _Exploring Sets and Maps in JavaScript_ (2019) Scotch.io, [read here](https://scotch.io/tutorials/exploring-sets-and-maps-in-javascript)