#JS from Start- Arrays and Array Methods.

in GitPlait2 years ago


It has been 6 days that I published the last #Jsfromstart. The last tutorial was about Template Literals. I explained in depth and I gave example in doing things in ES5 way and ES6 ways.

Today, we will look at arrays and array methods. Arrays are important aspect of any coding language. It allow us to store multiple values in a variable. In this tutorial, we will look at create arrays and mutating them with methods we have in JS.


const figs = [38,48,29,82,8,12];

You could do this in another way and both are arrays. Example:
const figs2 = new Array(28,38,72,12,43,2);

Now let's create another array of sport teams and they will be in strings. Array doesnt have to be numbers. 
const teams = ['Man United', 'Man City', 'Arsenal', 'Barcelona', 'Real Madrid', 'PSG'];

We can also have arrays of different data types. 
const joined = ['hey', 34, null, true, undefined, {a:1, b:1}, new Date()];

let fil;

Screenshot 313.png

Screenshot 314.png

How to get array length. This will show use how many values in have in an arrays.

fil = figs.length;

Now, let's check if a value in in array. Checking if something is in array.

fil = Array.isArray(figs);

Getting a single value in an array.

fil = figs[2]; Arrays are zero based so that count would start from 0. The index of 2 in the array is 29.

To change value in array.

figs[3] = 200;

To find the index of a value.

fil = figs.indexOf(8);

Mutating Arrays.

Push method is used to add on to the end of array.

unshift method add on to front of array

To remove from the end of array.

To remove from front.

To splice out value. This is a method to remove some values from arrays by using the index.

To reserve array.

Concatenation: This will concate the two arrays.

fil = figs.concat(figs2);

Sorting Arrays alphabetically.
fil = teams.sort();
Screenshot 319.png

If you want to sort numbers, using sort will sort only the first numbers in array. If you have 100, 23, 54, 37 and 3. 100 will come first because of the first number 1(00). So to ensure your sort works from smaller number to the highest, you need to pass in a function.

fil = figs.sort(function(a, b){ return a - b; });

Screenshot 320.png

Screenshot 321.png

You can also do this the other way. From highest number to the lowest.

fil = figs.sort(function(a, b){ return b - a; });


That will be all for today. I will continue on Saturday. Thank you!

GitPlait Curation Trial

Delegate to Gitplait and get 80% curation rewards

I am Mikes (@tykee). I am an engineer who loves to write, code, and create. I so much believe in constant learning in every aspect of life and this is one reason I love creating contents about code, tech, life, entertainment, and create educational apps and community. I strive to get better every day. This is not my best; my best is yet to come, and every day is a chance to grow better.