#11 JS Data Structures: Arrays

Ricardo Luz
9 min readMar 13, 2019

This article belongs to the JS Data Structures series, which will contain these articles:

  • Arrays
  • Stacks
  • Queues
  • Linked List (soon)
  • Sets (soon)
  • Dictionaries/maps (soon)
  • Hashes tables (soon)
  • Trees: Binary Search Tree (BST) (soon)
  • Trees: AVL Tree (soon)
  • Trees: Red-black Tree (soon)
  • Trees: Binary Heap / Heapsort (soon)
  • Graphs (soon)

Like any other programming language, JS supports arrays, arrays are the most simple data structure and help us to store data sequentially, let’s suppose that we want to store the animals in a zoo, without an array we could do in this way:

const animal1 = 'elephant';
const animal2 = 'monkey';
const animal3 = 'snake';
const animal4 = 'lion';

The problem is we need to create a variable for each animal, if the zoo has 1000 animals we need 1000 variables, manage this is hard and depending on the situation is impossible, imagine create a list of thousand people living in your city using variables.

To solve situations like this we could use an array, the same example above could be done in this way:

const animals = ['elephant', 'monkey', 'snake', 'lion'];

Simple right? Arrays give us extra powers to handle with more complex data sets!

Creating an array

There are many ways to create an array, we could do it using the new operator:

const myArray = new Array();

Is also possible to define the numbers of items in this way:

const myArray = new Array(9);

This is especially useful when you need to execute an operation with a fixed number of times, let’s say we want to print ‘hello’ 10 times, we could do it:

[...Array(10)].forEach(emptyItem => console.log('Hello'));

But the most common way to create an array is simply using [] instead of using New and Array words, like this:

const myArray = [];

Multi-dimensional arrays

Arrays allow us to create arrays inside arrays that generate 3D, 4D or xD arrays, let’s say that we store the results of a soccer game championship, we could do in this way:

const soccerChampionshipResults = [[3, 2], [0, 0], [1, 0], [4, 1]]

In this example, we build a 3D array, and we could access each result in the same way that we did before soccerChampionshipResults[0] will return [3, 2], soccerChampionshipResults[1] will return [0, 0] and so on.

Accessing the elements of an array

You could access an element inside an array point the cursor directly to the desired element like this:

const animals = ['elephant', 'monkey', 'snake', 'lion'];console.log(animals[2])

In this example you’ll get the third element (snake) of your array, the reason is the array pointer starts in 0.

const animals = [
'elephant', // element number 0
'monkey', // element number 1
'snake', // element number 2
'lion' // element number 3
];

If you need to know how many items the array has, you could use the length attribute:

const animals = ['elephant', 'monkey', 'snake', 'lion'];console.log(animals.length) // will return 4

Another method to access the elements inside an array is using forEach method:

const animals = ['elephant', 'monkey', 'snake', 'lion'];animals.forEach(animal => console.log(`Hello I am a ${animal}`));/* will outputHello I am a elephant
Hello I am a monkey
Hello I am a snake
Hello I am a lion
*/

You also could use map, reduce, filter, for..in, for..of depending that you want to do, if you want more about these methods I wrote some articles about this:

Creating new items inside an array

There are many different ways to add an item depending on which position you want to add this item, some examples are:

Adding an item at the beginning of an array

To add an item at the beginning of array you need to move the other items to a new position, you could do it in this way:

But the simplest way to do that is using the unshift function:

const animals = ["elephant", "monkey", "snake", "lion"];
animals.unshift('macaw');
console.log(animals); // will return [ 'macaw', 'elephant', 'monkey', 'snake', 'lion' ]

Adding an item at the end of an array

This is simpler than adding in the middle or in the begging, you could use the array.length to do that:

const animals = ["elephant", "monkey", "snake", "lion"];
animals[animals.length] = 'macaw';
console.log(animals); // will return [ 'elephant', 'monkey', 'snake', 'lion', 'macaw' ]

The array.length attribute always returns the number of items inside an array, you also could use the push method to add items in the end, like this:

const animals = ["elephant", "monkey", "snake", "lion"];
animals.push('macaw');
console.log(animals); // will return [ 'elephant', 'monkey', 'snake', 'lion', 'macaw' ]

Adding items in the middle (or in any position) of an array

The process to add in the middle is almost the same of adding the beginning, the difference is you’ll only move the items after the desired position:

You also could use the native method splice to do the same in a most simple way:

const animals = ["elephant", "monkey", "snake", "lion"];
animals.splice(2, 0, 'macaw');
console.log(animals); // will return [ 'elephant', 'monkey', 'snake', 'lion', 'macaw' ]

Where 2 is the position that you want to add and 0 is the total items that you want to remove after this position.

Removing items from an array

The methods to remove an item varies according to the position you want to remove an item.

Removing an item from beginning

To remove from the beginning you need to overwrite the first item with the second, the second with third and so on, after this we need to redefine the array length to ignore the last item:

Is better we use the approach of redefining the length than use delete, once delete will keep the last item without any value, like this:

const animals = ["elephant", "monkey", "snake", "lion"];
delete animals[3];
console.log(animals); // will return [ 'elephant', 'monkey', 'snake', <1 empty item> ]console.log(animals.length); // will return 4

You also could use the native method shift to do the item remotion in a most simple way:

const animals = ["elephant", "monkey", "snake", "lion"];
animals.shift();
console.log(animals); // will return [ 'monkey', 'snake', 'lion' ]

Removing an item from the middle (or any position) from an array

To remove from middle you need to move back all items after the position of the item that you want to remove, like this:

You also could use the method splice without a third parameter to remove the item that you want to:

const animals = ["elephant", "monkey", "snake", "lion"];animals.splice(2, 1); 
console.log(animals); // will return ["elephant", "monkey", "lion"]

Where 2 is the position of the item and 1 is the number of items that you want to remove.

Removing an item from the end of an array

Is very simple to remove an item from the end, you’ll need simply redefine the length to length -1:

const animals = ["elephant", "monkey", "snake", "lion"];animals.length = animals.length - 1;console.log(animals); // will return ["elephant", "monkey", "snake"]

You also could remove more than one item from the end defining length to length -x where x is the number of items that you want to remove.

animals.length = animals.length - 2;console.log(animals); // will return ["elephant", "monkey"]

Sorting an array

Default sorting

The most simple sorting method to organize the items in Unicode order is using the sort method:

const animals = ["elephant", "monkey", "snake", "lion"];
animals.sort();
console.log(animals); // will return [ 'elephant', 'lion', 'monkey', 'snake' ]

This method runs an in-place sort which means that this won’t generate a new array, instead of that it will replace the current array order.

Be careful when you have items with the lower and upper case inside your array once the upper case characters come first in Unicode Table, so an item like Zebra will be put before an item called alligator for example.

const animals = ["elephant", "monkey", "Zebra", "snake", "lion"];
animals.sort();
console.log(animals); // will return [ 'Zebra', 'elephant', 'lion', 'monkey', 'snake' ]

Custom Sorting

The sort method allows you to create your custom sorting algorithms, let’s say that you have an array with population list and you want to order this from the smallest to biggest population, you could do that:

const populationList = [10000000, 1000000, 500000, 600000];
populationList.sort((a, b) => a - b);
console.log(populationList);
// will return: [ 500000, 600000, 1000000, 10000000 ]

Reverse sorting

Is possible invert the items of an array using the algorithm below:

The idea is to go through the array till the middle, replacing each item to an item in the other side of the array, for example, replace the first by the last and the last by the first, the second by the last but one and so on.

Also, you could use the native method reverse() to do the same thing:

const animals = ["elephant", "monkey", "snake", "lion", "zebra"];animals.reverse();console.log(animals); 
// will return [ 'zebra', 'lion', 'snake', 'monkey', 'elephant' ]

The only difference is the reverse method run inside the current array, while the first approach generates a new reversed array.

Searching an array

Method indexOf

There are many ways to search an array in Javascript, let’s start with indexOf:

const animals = ["elephant", "monkey", "snake", "lion"];const haveMonkeyInList = animals.indexOf("monkey") > -1;
const positionWhereMonkeyWasFound = animals.indexOf("monkey");
console.log({ haveMonkeyInList, positionWhereMonkeyWasFound });
// will output: { haveMonkeyInList: true, positionWhereMonkeyWasFound: 1 }

When indexOf founds the searched element it returns the position where this element was found when indexOf doesn’t found the search element, it returns -1.

Method filter

The main idea of the filter method is to create a new array following some given condition but is also possible to use this to return a new array with searched items:

const animals = ["elephant", "monkey", "snake", "lion"];const animalsWithLetterE = 
animals.filter(
animal =>
animal.indexOf("e") > -1
);
console.log(animalsWithLetterE);// will output: [ 'elephant', 'monkey', 'snake' ]

In the example above we mixed the indexOf with filter method, but in this case, we are using indexOf to search a substring inside a string.

Method Includes

The ES7 spec brought to us the includes method that reduces this:

const haveMonkeyInList = animals.indexOf('monkey') > -1

To this:

const haveMonkeyInList = animals.includes('monkey')

Also, is possible to send an additional parameter defining from what position do you want to start the search:

const animals = ["elephant", "snake", "monkey", "lion"];console.log(animals.includes('monkey', 1));
// will return true because exists an element called 'monkey' from the item with index 1
console.log(animals.includes('elephant', 1));
// will return false because doesn't exists an element called 'elephant' from the item with index 1

Other arrays methods

toString()

Allows output the array content in string format:

const animals = ["elephant", "snake", "monkey", "lion"];
console.log(animals.toString());
// will output: "elephant,snake,monkey,lion"

join()

Like toString method allows us to output the array content in string format, but is possible define a different delimiter than a comma:

const animals = ["elephant", "snake", "monkey", "lion"];
console.log(animals.join('-'));
// will output: "elephant-snake-monkey-lion"

fill()

Allows replace the content of strings in an array with a new content

const animals = ["elephant", "snake", "monkey", "lion"];
console.log(animals.fill('animals'));
// will output: ["animals", "animals", "animals", "animals"]

Also is possible to define the start index and the final index of items that will be filled

const animals = ["elephant", "snake", "monkey", "lion"];
console.log(animals.fill('animals', 2, 3));
// will output: ["elephant", "snake", "animals", "lion"]

from()

Allows create a new array using an old one:

const animals = ["elephant", "snake", "monkey", "lion"];
const animalsCopy = Array.from(animals);
animals[0] = 'zebra';console.log(animalsCopy);
// will output: ["elephant", "snake", "monkey", "lion"]

If you to want to know more about Javascript and Data Structures I recommend these books:

  • You Don’t Know JS Serie by Kyle Simpson (My favourite)
  • Eloquent JS by Marijn Haverbeke
  • Head First Javascript by Michael Morrison
  • Secrets of the JavaScript Ninja by Bear Bibeault and John Resig
  • Learning JavaScript Data Structures and Algorithms by Loiane Groner

If you are a Portuguese speaker check out my Youtube videos about Data Structures in Javascript:

Thanks for reading! Feel free to hit the recommend button below if you found this piece helpful, also, please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

If this post was helpful, please click the clap 👏 button below to show your support! ⬇⬇

--

--