How to manage an array in JavaScript

let post = [...arrays];

Publication date: 22-12-2021

What is an array in JavaScript?

Arrays are a set of data within a variable. This data can be of any type: strings, numbers, booleans, functions, objects, and even other arrays.

How do we create an array in JavaScript?🤷‍♂️

Arrays are characterized by square brackets ([]). A variable is created and will contain the data you need and this data is enclosed within the brackets.

//Creating an array

let avatarLives = [ "Kyoshi", "Roku", "Aang", "Korra" ];
//Second way to crate an array

let avatarLives = new Array ( "Kyoshi", "Roku", "Aang", "Korra" );

Although the second way of creating an array uses parentheses, when printing this arrangement by console it will be represented by square brackets. It is more common to see they are created like the first example.

The data inside the array is called index. 👈 These are counted from zero.

let aRandomArray = [ "Index 0","Index 1","Index 2","Index 3","Index 4" ];

And as I mentioned at the beginning, arrays accept any data type.

const aLotOfData = [
"String example",
7,
true,
10+9,
"Even accepts math operations",
innerArrayFunction(){},
anObject = { message: "Objects too" },
[ "A multidimensional array" ]
];

Finding index or elements of an array in JavaScript

To access the index of an array we must write the name of the variable with the index number between square brackets.

let avatarLives = [ "Kyoshi", "Roku", "Aang", "Korra" ];

avatarLives [ 0 ];//Kyoshi⛰
avatarLives [ 1 ];//Roku🔥
avatarLives [ 2 ];//Aang🌪
avatarLives [ 3 ];//Korra🌊

JavaScript array methods

How to use JavaScript array length method?

Here the following question may arise: How to know how many index an array has? We may not have created that array and we need to know how many elements there may be to manipulate it. For this there is the method array.length, where array refers to the name of the variable that contains the array.

The length method will return the number of indexes that an array contains.

let avatarLives = [ "Kyoshi", "Roku", "Aang", "Korra" ];

avatarLives.length // It will print 4 because the array contains four elements

A small detail when we are manipulating arrays, the indexes are handled as numbers and therefore we can do operations with them.

Suppose we do not know what the last element of the avatarLives array is. When using the length method, it will return the number 4. That number can be processed so that it returns the last INDEX of the array.

let lastAvatar = ( avatarLives.length - 1 )
//So
let lastAvatar = ( 4 - 1 )// index 3
//And
let lastAvatar = "Korra"

Methods are functions that allow us to perform certain operations with arrays. Next we are going to see several of these methods and how they handle the index of an array.

As a tip, when talking about methods, they are preceded by a point and are used with variables.😉

For the next examples we will use the following array:

let videogames = [
"Zelda - Ocarina of Time",
"Warcraft III",
"GTA V",
"Pokemon Go"
];

How to use JavaScript array push method?

videogames.push( "Duel Links" );

//It will append the new game
videogames = [
"Zelda - Ocarina of Time",
"Warcraft III",
"GTA V",
"Pokemon Go",
"Duel Links"
];

How to use JavaScript array pop method?

videogames.pop( );//No arguments required

//It will erase the last index
videogames = [
"Zelda - Ocarina of Time",
"Warcraft III",
"GTA V",
"Pokemon Go"
];

How to use JavaScript array unshift method?

videogames.unshift( "Duel Links" );

//It will add the new game at index 0
videoJuegos = [
"Duel Links",
"Zelda - Ocarina of Time",
"Warcraft III",
"GTA V",
"Pokemon Go"
];

How to use JavaScript array shift method?

videogames.shift( );//No arguments required

//It will remove index 0
videogames = [
"Zelda - Ocarina of Time",
"Warcraft III",
"GTA V",
"Pokemon Go"
];

How to use JavaScript array splice method?

videogames.splice( 0, 2 );
//First argument (0) specifies the index from where the element is going to be removed, the second argument (2) how many elements are going to be removed

//Result
videogames = [
"GTA V",
"Pokemon Go"
];

How to replace an item on an array in JavaScript?

To carry out this task, it is done in a very similar way when we want to find the index of an array element.

videogames [ 0 ]

And now we assign a new value to that index.

videogames [ 0 ] = "Silent Hill 2"

//Result
videogames = [
"Silent Hill 2",
"Pokemon Go"
];

Even this way we can add a new element to our array.

videogames [ 2 ] = "The Force Unleashed 1"

//Result
videogames = [
"Silent Hill 2",
"Pokemon Go",
"The Force Unleashed 1"
];

How to know the index of an item in an array in JavaScript?

The indexOf method

If we know the value of the data we are going to query, this method is the appropriate one.

videogames.indexOf ( "Silent Hill 2" );

//Result
0

At this point I remind you that the same array is being manipulated for all examples, so the results are sequential.😆

How to convert an array into a string?

The join method

let videogamesToString = videogames.join ( ", " );

//Result
"Silent Hill 2 ,Pokemon Go, The Force Unleashed 1"

The argument within the join method will determine how the strings within the string will be separated.

How to convert a string into an array using JavaScript split method?

let newVideogames = videogamesToString.split ( ", " );

//Result
newVideoJuegos = [
"Silent Hill 2",
"Pokemon Go",
"The Force Unleashed 1"
];

How to sort the elements of an array?

newVideogames.sort ( );

//Result
newVideogames = [
"Pokemon Go",
"Silent Hill 2",
"The Force Unleashed 1"
];

The sort method will sort alphabetically as long as the data in its indexes are strings. It will take as a priority the text strings that start with capital letters.

Numeric data will be sorted in ascending order taking into account only the first digit. If we have numbers like 18, 1, 2, 27, 5, 3 and 53 it will sort them as [1, 18, 2, 27, 3, 5, 53];

Boolean data will be taken as text strings.

The sort method's hierarchy order will be numbers > strings.

How to invert the order of the items of an array using JavaScript reverse method?

newVideogames.reverse ( );

//Result
newVideogames = [
"The Force Unleashed 1",
"Silent Hill 2",
"Pokemon Go"
];

The reverse method also takes into consideration the same points as the sort method.

How to concatenate two arrays into one?

Javascript concat method

This example will require a new array.

let moreGames = [ "Zelda - Majoras Mask", "Contra" ];

//Using concat method

let allGames = newVideogames.concat ( moreGames );

//Result
allGames = [
"The Force Unleashed 1",
"Silent Hill 2",
"Pokemon Go",
"Zelda - Majoras Mask",
"Contra"
];

Javascript Spread operator

The Spread Operator works in a similar way to the previous method but its syntax is much shorter. The ellipses are used before the variable.

let moreGames = [ "Zelda - Majoras Mask", "Contra" ];

//Using spread operator

let allVideogames = [ newVideogames, ...moreGames ];

//Result
allVideogames = [
"The Force Unleashed 1",
"Silent Hill 2",
"Pokemon Go",
"Zelda - Majoras Mask",
"Contra"
];

//For didactic reasons this code was repeated for the example😆

How to iterate an array using a for loop?

Some times we need to print the contents of an array, for this we are going to look at for loops.

Using JavaScript for loop to iterate an array

The traditional for loop is composed of three parts: the initialization of the variable, the condition and the operation. Each of the parts separated by a semicolon ( ; ).

//As pseudo code:

for ( initialization; condition; operation ) {
// Code to be executed as many times as indicated by the condition
}

To iterate the example array of allGames would be like this:

for ( let i = 0; i < allGames.length; i++ ) {
console.log ( allGames [ i ] );
}

Initializing the variable with the letter i is a standard for this kind of operation. You can use any variable you want to execute a loop. There are cases where there are loops within loops and letters of the alphabet close to i such as j or k are used; it is also done for the convenience of writing a simple variable within all that code.

The condition in this case is if i (which is zero) is less than the number of indexes in the array (allGames.length = 5) it increases by one (i++).

The operation can also be expressed as i = i + 1 and even determine how many steps the operation should be performed, but it does not apply for this example.

The result of this loop is the printing of each items inside the array. Why? The i inside the square brackets is going to indicate the element to be printed. Remember I mentioned above that indexes are handled as a number? It translates to something like this:

allGames [ i ] // i = index position
//So
allGames [ i = 0 ]
//So
allGames [ i = "The Force Unleashed 1" ]

//Now the operator sums 1

allGames [ i = 1 ]

allGames [ i = "Silent Hill 2" ]

// Sum 1 again until i = 5

Using JavaScript forEach loop to iterate an array

The forEach method is an easier way to iterate an array. In this case we will have to pass it as a parameter a function that takes the elements inside the array.... WTH??? 😆 Let's watch it.

//Remember that we have the array in this form:

allGames = [
"The Force Unleashed 1",
"Silent Hill 2",
"Pokemon Go",
"Zelda - Majoras Mask",
"Contra"
];

//Using the forEach method

allGames.forEach ( game => {
console.log ( game );
}

The variable game is going to refer to the elements inside the array. The name of this variable can be whatever you want but the standard is for it to be the singular of the array variable name and for the indexes to be displayed they are sent to print to the console. The function parameter and the variable inside the console printout must be the same for it to work.

Understanding the JavaScript multidimensional arrays

Multidimensional arrays are those that have arrays inside arrays. It's simple like that.😂 They can be viewed as follows.

const inception = [ "Main Dream", [ "2nd dream level", [ "3rd dream level", [ "Here is Leonardo DiCaprio's psycho wife" ]
] ] ];

In the inception array there are different levels of arrays. In the first level we have the "Main Dream"; this is the one that occupies all the levels or dimensions of the array.

The "2nd dream level" occupies its space plus the lower levels.

The "3rd dream level" occupies its space plus the dream space where the one who falsely died in The Dark Knight Rises DiCaprio's psycho wife is located.

Let's see how the same cast of The Dark Knight and DiCaprio would enter the different levels of the array:

//Main Dream

inception [ 0 ]

//2nd dream level

inception [ 1 ]

//3rd dream level

inception [ 1 ] [ 1 ]

//For God's sake Leo...

inception [ 1 ] [ 1 ] [ 1 ]

Multidimensional arrays have the same index ordering rules as a regular array. Using this kind of arrays is often confusing and it is not very common to see too many levels.

If you found this article useful, let me know through my social networks (at least until I implement a comments section.🤣) If you didn't understand anything read it again. And if you like Avatar which is your favorite character and why Toph Beifong?