keemosty

Hakeem Abdul

Posted on October 12, 2020

Arrays

Introduction To Arrays

ghost.gif

What Are Arrays?

Arrays are single variables ( objects ) which can contain many data values (types ) in them arranged in a list. These values are enclosed in a square brackets and are seperated from one another by a comma.

An Array can hold multiple data values in itself and therefore can store a wide range of information in its variable.

An Array does not have a data type of its own.

Arrays are objects

FB_IMG_15015091573116806.jpg

Arrays are very important in the fact that they help in storing data(values) in a collective list and provides you with the easy accessiblity to get the individual content of each list item in the array and use them in your code. This beats the other alternative of you having to declare a variable individually for every single item(data) you want to use in your code.

If for example, you want create a variable to store the list of the types of watches you're selling on your business website, then an array should be the way to go instead of creating different variables for each of the watches you want to store in it.

Difference Between An Array And An Object.

If you have come across an object, then you would realize that an array and an object sometimes may get complicatedly similiar in ideas. The difference here is that an Array holds multiple data, all of which relates to certain type, purpose or kind. For example,

  • A list of all the names of the lawyers in a particular firm.
  • A list of the cars driven by the employees in a hospital.

...An object on the other hand, is best used as a variable set to contain the overall information relating to a particular item.

  • A data set of a lawyer's fullname, age, address, eyeColor etc.
    • A data set of a car's name, speed rate, color, etc.

Creating An Array

An array can be created in two ways

  • An Array constructor function

    const myArray = new Array();

  • An Array literal syntax

    const myArray = [];

These arrays are all empty as there are no data values in them yet.

The first way may lead to complications, it is highly recommended you use the second way(Array literal syntax).

Storing Data Values In An Array

let footballTeams = [`Barcelona`, `Liverpool`, `Chelsea`, `Juventus`];
Enter fullscreen mode Exit fullscreen mode

From the code example above, we have created a variable footballTeams and assigned an array of teams listed in the square brackets all seperated by a comma from the other.

Arrays dont have to contain only one data type (string) but can contain different data types all enclosed in the same array(string, numbers, boolean etc).

let myArray = [`Tino`, 20, true, `developer`];
Enter fullscreen mode Exit fullscreen mode

Here, you'll see that the array contains different data types stored in it. This is an efficient way of storing information, profiles etc on your variables.

Here's another tip! we can also store an array(s) inside another array.

let avengers = [`iron man`, `captain america`, `thor` [`hawkeye`, `falcon`, 2020]]
Enter fullscreen mode Exit fullscreen mode

From the code, you'll notice that inside the array, there is another array holding an information of two strings and a number.

Array(s) inside another array are called multidimensional arrays

Accessing Items From Arrays

The items or elements in an array sometimes may be needed to be accessed and used individually or perform certain tasks like loop iteration and so on.

The items in an array can be accessed using a method called the Bracket Notation.

The items each have a number tag or position that enables them to be accessed individually. This is called the Index Number.

let books  = [ 
    `comedy`,
    `thriller`,
    `action`,
    `drama`,
    `sci-fi`
];
Enter fullscreen mode Exit fullscreen mode

In this instance, we have created an array of book genres and in order to access any of them, we employ the method above called the bracket notation.

We do this by using the bracket symbol [] and then writing into the bracket; the index number of the array-item we intend on getting.

The index number counts from 0 for the first item. That is,

  • first item = 0
  • second item = 1
  • third item = 2

Note: Computers generally start counting from 0.

And so on...

Therefore...

let books  = [ 
    `comedy`,
    `thriller`,
    `action`,
    `drama`,
    `sci-fi`
];
Enter fullscreen mode Exit fullscreen mode

...accessing all array-items will then be

books[0];
//comedy
books[1];
//thriller
books[2];
//action
books[3];
//drama
books[4];
//sci-fi
Enter fullscreen mode Exit fullscreen mode

Printing the code above on your browser console using the console.log() will give you all the results of all the array-items on your console.

Note that we said that array and objects were different in some cases, but the truth in general is that arrays are technically still objects. Still its best to refer to them as arrays to avoid complications.

Using the typeof operator on an array will return a result of object

let sports = [
`basketball`,
`football`,
`volleyball`
];
console.log(typeof (sports));     // Object
Enter fullscreen mode Exit fullscreen mode

Numbered Indexes

The method used in the previous example, made use of the bracket notation and the indexes of each of the elements (items) in the array to access them individually.

This is what is meant by arrays using numbered indexes.

Arrays with named (using letters) indexes are called associative arrays

It is not advisable to use associative arrays in javascript as they lead to complications in your code

Use numbered indexes instead.

let colours  = [`black`, `blue`, `red`, `teal`]

// Accessing the red here
colours[2]; // gets the red item with the index of 2

console.log(colours[2]); // Prints out the result on the console
Enter fullscreen mode Exit fullscreen mode

Another thing to note here is that the javascript parser is white space insensitive as similar to the browser engine.

So, in order for a cleaner code, your array can be arranged like this

let colours  = [ 
    `black`,
    `blue`,
    `red`,
    `teal`
]    
Enter fullscreen mode Exit fullscreen mode

NOTE:

  • A function can be an element in an array
  • An object can be an element in an array
  • Even an array can be an element inside another array.

Properties Of An Array

The Length Property

This is the most important property of an array and probably the only one you may need to use practically in your code.

The length property is a property attached to an array (object) that calculates and outputs the number of elements (items) in an array.

The length property is used to determine the number and as the name implies, the length of an array. It is very useful in loops iteration.

// Define an array books with elements

let movies  = [`comedy`, `thriller`, `sci-fi`, `drama`, `action`];

// Prints the length of the array on the console

console.log(movies.length);  // 5

Enter fullscreen mode Exit fullscreen mode

The length property returns the result of 5 which is the number of the elements in the array books.

Looping Through An Array With The Length Property

A For loop is used best to loop through the items in an array

Note: We loop through arrays in order to perform a number of operations on the items of the array based on a laid out condition.

//Declaring the variables to be used in the loop iteration
let movies, count, i;

// Initializing the array
movies  = [`comedy`, `thriller`, `sci-fi`, `drama`, `action`];

//Initializing the variable count and assigning it to the length of the array
count = movies.length;

//For loop iteration
for (i = 0; i < count; i++){ 
console.log(  movies[i] )
//Results will be...
//comedy
//thriller
//sci-fi
//drama
//action
}; 
Enter fullscreen mode Exit fullscreen mode

Other properties of an array are

  • Constructor property
  • Prototype property

Now that we have gotten a pretty deep introduction to arrays, lets turn a chapter and take a look at the most important and powerful things about arrays......the array methods.

ARRAY METHODS

Arrays have built-in functions that perform specific operations on the elements in the array and the array as a whole itself. These built-in functions are called methods.

Methods are basically special functions of objects that performs certain action on them and technically arrays can be referred to as objects.

Arrays have over 20 valid methods that can be used on them but we are only going to go over the major ones.

The Pop() Method

pop.gif

The pop method pops out or removes the last element (item) from an array.

let fruits = [`oranges`, `apples`, `pineapples`, `mangos`];

fruits.pop(); // fruits =[mangos]
Enter fullscreen mode Exit fullscreen mode

The pop() method here removes the last item from the list, which in this case is mangos and then returns a new array with the value of the element(s) that was removed. That is...

fruits.pop() = [`mangos`];
Enter fullscreen mode Exit fullscreen mode

This changes the initial list of the array, therefore...

fruits = [`oranges`, `apples`, `pineapples`];
Enter fullscreen mode Exit fullscreen mode

Using the pop() method on an empty array [ ] will return the keyword undefined as the result.

The Push() Method

push.gif

This is basically the opposite of the pop() method as the push() method is used to push in or add an element to the end of an array.

let languages = [`english`, `spanish`, `french`];

let newLang = languages.push(`hindi`);

console.log(languages); // ["english", "spanish", "french", "hindi"]

console.log(newLang);  // 4
Enter fullscreen mode Exit fullscreen mode

The array languages was created and stored in it was a string of 3 words(languages).

The push() method takes the parameter(s) to be added in the brackets, separated by commas.

The variable newLang was created and used to store the altered array created as a result of adding in a new string to the end of the array using the push() method..

The initial array languages is now modified . It now produces a result of four strings including the newly added one.

The variable newLang produces a result of 4 which is now the length of the new array.

The Unshift() Method

The unshift() method is used to add new element(s) to the beginning of an array. This works like the previous push() method, only that instead of adding element(s) to the end of the array, the unshift() method adds from the beginning of the array.

// Initializes the tvSeries array
let tvSeries = [
    `The Walking dead`,
    `Game Of Thrones`,
    `Into The Badlands`
    ];

//Adds new elements to the tvSeries array using the unshift() method and then stores the result in the newList variable
let newList = tvSeries.unshift(`The Witcher`, `Blackish`);

//Prints the result of the newly altered array on the console
console.log(tvSeries);

//Prints the results of the length of the altered array on the console
console.log(newList);
Enter fullscreen mode Exit fullscreen mode

array_unshift_pic1.png

array_unshift_pic2.png

The Shift() Method

The shift() method is the opposite of the previous unshift() method. The shift() method is used on arrays to remove or shift out the first element in a list.


//Creates a entertainers array with three strings data
let entertainers = [`Davido`, `Burna Boy`, `Wizkid`];

//Creates a removed variable, removes the first element from the original array and saves the results in the variable 
let removed = entertainers.shift();

//Prints out the results of the altered array on the console
console.log(entertainers);

//Prints out the result of the first element that was removed on the console
console.log(removed);

Enter fullscreen mode Exit fullscreen mode

array_shift_pic1.png

array_shift_pic2.png

The Concat() Method

This method is used to concatenate (add) two or more arrays together.

A new array is created to store the results of the added arrays. The original arrays are left untouched.


//First array
let oldArtistes = [`Davido`, `Burna Boy`, `Wizkid`];

//Second array
let newArtistes = [ `Fireboy`, `Rema`, `Omah Lay`];

//Adds the two arrays with the concat() method and stores it in the allArtistes variable
let allArtistes = oldArtistes.concat(newArtistes);

//Prints the results of the first array which still remains the same
console.log(oldArtistes);

//Prints the results of the second array which stays the same
console.log(newArtistes);

//Prints the results of two arrays merged  together into one
console.log(allArtistes);

Enter fullscreen mode Exit fullscreen mode

array_concat.png

NOTE: In a case of adding more than one arrays, the same method is employed, only in this case...

The arrays to be added are put in the parantheses seperated from each other with a comma, e.g:

let totalArray = array1.concat(array2, array3, array4....arrayn);

Enter fullscreen mode Exit fullscreen mode

The Join() Method

This method as the name implies joins all the elements in the array and returns them in a string format. The unique thing about this method is the fact that you can specify the separator used to separate the elements (, * - .etc)

let countries = [`Nigeria`, `Ghana`, `Egypt`];

let elements = [ `Hydrogen`, `Oxygen`, `Carbon`];

let athletes = [`Ronaldo`, `Jordan`, `Anthony`];

//uses a * operator to seperate the elements
console.log(countries.join(`*`));

//uses a , operator to seperate
console.log(elements.join(`,`));

//Uses a  (backspace) to seperate
console.log(athletes.join(` `));

Enter fullscreen mode Exit fullscreen mode

array_join.png

NOTE:

  • The join() method by default uses the comma ( , ) operator to seperates the elements
  • The operator to be used in the join() method is to be put in the parantheses and inside the backticks ( ES6 template literal ).

The Splice() Method

This method is used to add, remove or replace element(s) in an array.

Syntax

The syntax of the splice() method is a little tricky...
The splice() method takes three parameters into its parameters which are

  1. The index position of the element(s): this is the index number to start the counting from..
  2. The number of elements to be removed from the array
  3. The new element(s) to be added (*if two or more, separate with a comma)

testArray.splice( index number, No of elements to be removed, newelement1, newelement2....newelementn)

let planets = [`mercury`, `venus`, `jupiter`, `saturn`];

let splicedPlanets = planets.splice(2, 0, `earth`, `mars`);

console.log(planets);

console.log(splicedPlanets);

Enter fullscreen mode Exit fullscreen mode

array_splice_pic1.png

Explanation

  • The array planets was declared, and four string data was stored in it.
  • A variable splicedPlanets was created, and it was used to store the results of the product of the splice() method on the planets array.
  • The splice() method based on its parameters given was used to add two new elements into the array.
  • The method started its counting from index number 2 which was jupiter, it cuts out none of the elements due to its value for the no-of-elements-to-be-removed being 0, finally it places(adds) the two strings in its parameter in front of index no 2 where it started its count from. Hence its results..
  • If you noticed, the last result that was printed on the console returned an empty array [ ], this is because elements were added and not removed, so there wasnt any element(s) left to be returned to the new array stored in the splicedPlanets variable.

Another Example

let boardGames = [`scrabble`, `monopoly`, `yahtzee`, `ludo`, `risk`, `clue`];

let splicedGames = boardGames.splice(2, 2, `battleship`, `candy land` );

console.log(boardGames);

console.log(splicedGames);
Enter fullscreen mode Exit fullscreen mode

array_splice_pic2.png

Explanation

  • A boardGames array was created and used to store 6 strings
  • A splicedGames variable was created and used to store the product of the splice() method on the array.
  • The first parameter in the splice() method is 2, which means the counting started from index position 2 (yahtzee).
  • The second parameter is 2 which means the no-of-elements-to-be-removed was two (yahtzee & ludo).
  • The last parameter which took in the new element(s) was contained by two strings (battleship & candy land). Therefore, this new elements replaced the position of the ones that were removed from the array. Hence the results...
  • Again, if you notice that the last result on the console is giving us an array with two strings. This strings are the ones that were removed from the array and then finally returned to this new array that was stored in the splicedGames variable.

The Slice() Method

slice.gif

This method is often confused with the splice() method, because of how they both sound and thier functions.

The slice() method is used to slice out or cut out a piece (copy) of the elements of an array based on its parameters given. It creates a new array for the piece that was cut out from the original array.

Syntax

The slice() method takes in two parameters...

  • The first parameter is the starting index number.
  • The second parameter (optional) is the ending index number. >NOTE: The ending parameter is optional, since the first describes where to start from when slicing out the elements from the array, if the ending parameter is not defined, the rest of the element is cut out from the array starting from the index position in the first parameter.
let pizzas = [`cheese`, `veggie`, `pepperoni`, `buffalo`, `margherita`, `hawaiian`];

let slicedPizzas = pizzas.slice(2 );

console.log(pizzas);

console.log(slicedPizzas);

Enter fullscreen mode Exit fullscreen mode

array_slice_pic1.png

Explanation

  • The array pizzas was created, and 6 strings were stored in it.
  • A slicedPizzas variable was created and used to store the product of the slice() method on the array.
  • The method took one parameter 2 which was the starting index number (ending parameter optional).
  • From the index position of 2: (pepperoni), the rest of the elements in the array was cut out. This is because the ending parameter wasnt defined. Hence the results...
  • Lastly, you'll notice that the original array results printed on the console stayed intact, this is because only a copy of the sliced array was cut out.

Another Example

let music = [`jazz`, `rock`, `pop`, `hip hop`, `classical`, `afro beats`];

let slicedMusic = music.slice(1, 3 );

console.log(music);

console.log(slicedMusic);


Enter fullscreen mode Exit fullscreen mode

array_slice_pic2.png

Explanation

  • The array music was created, and 6 strings were stored in it.
    • A slicedMusic variable was created and used to store the product of the slice() method on the array.
    • The method took two parameters 1 & 3 which were the starting index number and the ending index number respectively.
    • From the starting index position of 1: (rock) to the the ending index position of 3 (hip hop), the elements in between the defined positions in the array were all cut out excluding the last index which was 3: hip hop. Hence the results...

The Sort() Method

This method is used to compare and arrange elements of an array in an ordered pattern. The default pattern is alphabetically (for letters) and ascending (for numbers).


let shoeBrands = [`vans`, `jordan`, `puma`, `adidas`, `reebok`, `nikes`];

let sortedBrands = shoeBrands.sort();

console.log(shoeBrands);

console.log(sortedBrands);


Enter fullscreen mode Exit fullscreen mode

array_sort_pic1.png

Explanation

  • The array shoeBrands was created and 6 strings were stored in it.
  • The variable sortedBrands was created and used to store the product of the sort() method on the array.
  • The two results are all the same on the console as the method arranges all the elements in alphabetical order and alters the original order of the array.

Another Example

let numbers = [79, 1, 25, 10000];

numbers.sort();

console.log(numbers);

Enter fullscreen mode Exit fullscreen mode

array_sort_pic2.png

Explanation

  • The numbers array was created and used to store 4 number data types.
  • The sort() method was used on the array.
  • Although, the largest number there was 10000, it came second as sorted out by the method. This is because computers generally operates on 1's and 0's, therefore according to computer maths(binary), 10000 < 25 & 79. Hence the results...

The Reverse() Method

reverse.gif
The reverse() method as the name implies is used to reverse the order of elements in an array.

let routine = [`wake up`, `say a prayer`, `brush my teeth`, `take a bath`, `go to work`, `sleep`];

let reversedRoutine = routine.reverse();

console.log(routine);

console.log(reversedRoutine);

Enter fullscreen mode Exit fullscreen mode

array_reverse.png

Explanation

Without a need for much explanation, the workings of the reverse() method are quite obvious. It reverses the order or arrangement of the array and returns a new array with the elements arranged backwards.

NOTE: The original array is now altered and will give the same results as when its reversed.

Conclusion

vlcsnap-2020-10-01-09h12m14s550.png

This has been a pretty long ride, hope you enjoyed it. As much as we did, not all of the array methods were covered in this article for the sake of length and the case of too-much-information-ritis . Some important ones left out were

  • forEach()
  • map()
  • filter()
  • reduce()...

You"ll want to check this ones out as they are really powerful too when it comes to array iteration

THANK YOU!

success.gif
Thank you for reading, your time invested is appreciated. Please leave a message if you found this article helpful or you have more to contribute.

💖 💪 🙅 🚩
keemosty
Hakeem Abdul

Posted on October 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ELOQUENT JAVASCRIPT : CHAPTER 3
javascript ELOQUENT JAVASCRIPT : CHAPTER 3

December 12, 2020

Arrays
javascript Arrays

October 12, 2020

What is Event Loop in JavaScript?
javascript What is Event Loop in JavaScript?

September 17, 2020

JS Quiz
javascript JS Quiz

August 20, 2020