Array in Javascript | Working Examples with Useful Methods
Working with Arrays is quite fun in Javascript. I made this tutorial on Array in Javascript to help you understand some of the useful methods that you can use to get the most out of an array. We will start with the basic ones and then delve into more complex ones gradually.
Alright without further ado, let’s get started with Array in Javascript.
The first thing you gotta do is open your IDE. I am using Visual Studio Code or VSC which I find really convenient to work with. It is very clean and easy to use. You can install Visual Studio Code too if you want.
An Example of an Array in Javascript
Let’s create a small array, to begin with.
let age = Array[5]; //only declares the array with size
The above line would only declare the array. If you try to print age at this point you will get undefined.
Because what we have done is just created an array with five indices with nothing in it.
We need to define it with some values inside. To do that we need to create a new object. Kind of similar to the concept of classes and objects in Java.
Let’s create a new object of this array using the new constructor.
age = new Array(13,36,67,34,76); //array defined with new object
There now you have now the variable age defined with 5 values in each index.
You can now print the value to display the array using console.log(age).
You will get the result:
[ 13, 36, 67, 34, 76 ]
But why go through all that trouble when you could have simply put all of it in one line?
Yes, you can declare and define the variable in one line just like in Java.
Just merge the two lines like this:
let age = new Array(13,36,67,34,76); //define and declare in one line
That’s it!
As you can see from the output above, it fetches the same result.
A Quicker and Better Way of Defining Arrays
Why do you need to use new keyword? Just get rid of it! Javascript is really intelligent!
Just use the goddamn square brackets!
Square brackets automatically tells Javascript that you are dealing with an array.
So the above would become:
let age = [13,36,67,34,76]; //use square brackets to define and declare an array
Now that you would run it, it would fetch you the same result as can be seen in the image below:
Useful Array Methods in Javascript
There are plenty of methods you can use while working with Arrays. What you can do hereon, since your IDE comes packed with Intellisense, just type the name of your array variable that you created, in this case ‘age’ and press the ‘.’ button. You will notice a bunch of methods will flare open.
One by one you can console log these methods to understand what they do.
We are going to see a bunch of these in the Arrays in Javascript tutorial. These are the most commonly used methods and the most useful ones too.
The first one is of course when you want to find out the length of an array.
Length
Just type array.length and find out the length of the array in question.
Just type console.log and then inside brackets age.length to grab the length of the array.
Notice how you don’t have to add braces in the end, unlike Java.
The above gave you 5 which is the correct length of this array.
Index Of method in Javascript Array
The next useful method is called indexOf which tells you the index of the element in an array.
Very useful in finding out the location of an element when you are dealing with big documents to target that one word or element you are looking for.
Type the following:
age.indexOf(67)
Console log the above and you get the index of the element 67 which in this case is located at the third position. Since an array index starts from 0, the answer would be 2.
Let’s check by typing:
console.log(age.indexOf(67))
Let’s run our program and the answer is drum rolls:
2
The whole code looks something like this:
Push
The next useful method is called push. You use push when you want to append an item to an array. The item will get added to the last index of the age variable.
Remember we need to provide the item information in brackets this time to tell Javascript what needs to be added.
Go ahead and type:
age.push(item)
where replace the item with the stuff you want to append.
I am going to add 25 to the existing array.
Now console.log age variable once again. You will get the following result:
[ 13, 36, 67, 34, 76, 25 ]
Our full code would look like this:
Pop
As opposed to push, you have got a pop method that removes the last element of the array.
Trying it on our existing age variable.
Just type:
age.pop()
and then console.log(age) once again to check if the last element got chucked out:
It did! I am getting this now:
[ 13, 36, 67, 34 ]
The final code looks like this:
Unshift
What if you want to add an element at the beginning of an array?
That’s where unshift method comes in handy. Let us add a number to the front.
Just type:
age.unshift(44)
where 44 is the number I wish to add before the starting point of the array.
Let’s run console.log(age) again and:
[ 44, 13, 36, 67, 34, 76 ]
Boom! Added!
Includes
The includes method is one of the important ones that you might need again and again while working with arrays. It is used to check if the element you are searching for is present in the array or not.
It gives a boolean value of true or false as output.
Go ahead and type:
age.includes(67)
where 67 is the number that I am trying to search if present or not.
console log it to check if it is present or not.
console.log(age.includes(67))
Run the program and the output is:
true
Here’s what the overall code looks like:
Simple right?
Slice
What if you wanted to grab another array from an existing array? You want to slice a big array into a smaller array to work on some bits, that’s where the slice method comes in for the rescue.
The slice method takes indices as starting and ending points. The end index is not included. So you gotta count carefully the last index you want.
Let’s see that using an example:
Type:
age.slice(1,4)
In our age array, 1 would mean 36, and 4 would mean 76, but 76 is not included. So our last element would technically be 34.
You can of course put this into another array, but I am gonna just console log it and show you:
console.log(age.slice(1,4)
would give you the output as:
[36, 67, 34]
Here’s the full code with the output:
Reduce
When you want to perform an activity on an array where you need to ‘accumulate’ your results into a variable, you can make use of the reduce method.
Let’s say you want to add all the numbers present in the array age.
You can make use of the existing callback function of the reduce method to write your code in just one line.
Here’s how:
Type:
age.reduce((sum, total) => sum + total, 0)
We have used an anonymous function with arrow functions released as part of ES6 to make our code look shorter.
Let’s put that in a variable called totalAge.
let totalAge = age.reduce((sum, total) => sum + total, 0)
Let us now print the totalAge using:
console.log(totalAge);
The whole code would look something like this:
Output it and you get:
226
which is nothing but the result of the addition of all the elements in the array.
You might have alternatively achieved it using for loop with the following method:
sum = sum + age[i]
replacing ‘i’ with the indices of your array and printing ‘sum’ in the end.
Doesn’t the reduce method save time?
Filter
Similar to the reduce function there exists a method called filter which filters your array based on your specified condition in just one line of code.
Let’s say your condition is to only grab the even methods from an array, that’s where filter method comes in handy.
How do you grab even numbers? By dividing a number by 2 and then checking the remainder to be 0 right?
So basically this condition:
number % 2 == 0
Let us use the same logic in our filter to filter out all the even numbers from age array.
Simply type:
age.filter(even => even%2 == 0)
Now let’s put this in a variable called evenAges
let evenAges = age.filter(even => even%2 == 0)
and then print evenAges out::
console.log(eventAges)
Our whole code will look something like this:
When we run the above we will get the result as
[36, 34, 76]
which are the even numbers in our array.
Easy peasy right?
More stuff is coming here. Watch this space.
1 Response
[…] more in-depth practical example tutorial on Array is available here for […]