In this tutorial, we will learn how to use array in javascript, by the end of this course you will be able to create an array in javascript, use the most important array's methods and you will know how to use them in a real-life project so let's start.
What's an array?
An array is a data structure consisting of a collection of elements, each element has his own index that will allow us to access it. In other terms, an array is a list of items, like your shopping list for example.
It's important to learn how to use arrays because you will need it in many of your web application, let me give you an example:
- imagine that you want to an e-commerce website, in every e-commerce website there is a shopping list, to store that shopping list or to apply some modification to that list you will need to use an array to be able to do it.
N.B: by default array index start at 0
How to create an array on javascript?
Nice question, in javascript it's easy to create an array, let's see how by an example:
//Creating an array
let ShoppingList = ['Computer', 'Mouse', ' keyboard', 'Headsets'];
So, in this sample, we have created an array called ShoppingList, we used the keyword let or you can also use var, then we opened brackets and we put our elements inside those brackets as you can see elements are separated by a comma ','.
in our example, we have created an array of string, we can make an array of any kind of object, it can be an integer, boolean, or even a javascript object.
now let's try to print this array in our console and see the result
in our example, we have created an array of string, we can make an array of any kind of object, it can be an integer, boolean, or even a javascript object.
now let's try to print this array in our console and see the result
let ShoppingList = ['Computer', 'Mouse', ' keyboard', 'Headsets'];
console.log(ShoppingList)
console:
['Computer', 'Mouse', ' keyboard', 'Headsets']
now imagine that we want to display only the first element, then it's simple we will only tap
arrayName[index];
now let's back to our example, we will display the first element
//displaying the first item
let ShoppingList = ['Computer', 'Mouse', ' keyboard', 'Headsets'];
console.log(ShoppingList[0])
now we will see how to modify the first element of our array, for this we will write this code:
arrayName[index] = the value that you want
let's go back to our example and change the value of our first element
//Changing items value
let ShoppingList = ['Computer', 'Mouse', ' keyboard', 'Headsets'];
console.log(ShoppingList)
ShoppingList[0] = "Macnbook";
console.log(ShoppingList)
console:
['Computer', 'Mouse', ' keyboard', 'Headsets']
['Macnbook', 'Mouse', ' keyboard', 'Headsets']
ForEach in JavaScript
in the previous section, we saw how to print an element inside an array an how to modify it, we also so how to print our array inside the console, but what if we want to browse each element inside our array one by one. for this, we have two solutions, the most popular solution is to use a for loop like this
//browse our array's items one by one
let ShoppingList = ['Computer', 'Mouse', 'keyboard', 'Headsets'];
//Create a for loop
for(var i = 0; i < ShoppingList.length;i++){
console.log(ShoppingList[i]);
}
in this example, we have used the length property, the length property return the number of elements in an array, in our example, we have 4 elements so it will return 4
as you can see we have created a for loop that will start from 0 and will stop at
ShoopingList.length-1
The second solution and the most simple one is to use forEach() method, in this tutorial we will not see everything about foreach, we will only see an example about it.
to display each item in an array using forEach we will use the syntax below:
//syntax
arrayName.forEach( function(ElementToDisplay) {
//ElementToDisplay Represent the array items
console.log(ElementToDisplay);
});
if we apply this to our example then we will write like this:
//browse our array's items one by one
let ShoppingList = ['Computer', 'Mouse', 'keyboard', 'Headsets'];
//Using forEach()
ShoppingList.forEach(function(items){
console.log(items);
});
Javascript array Methods
now let's see the most important part of this tutorial, we will see the most important array's method that you will probably use frequentlyin this section, we will use another example and we will use another array that will illustrate a true shopping list
we will make an array of objects that will have 3 property, the name, the price, and the quantity
like this:
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
filter()
the filter() methods allow you to create a subarray of an existing array by filtering it using a condition.
imagine that you want to display only the element where the price is less than 5000$, we can use a for loop and add an if condition but it's too long and there is a simplest way, we will use the filter method
syntax:
imagine that you want to display only the element where the price is less than 5000$, we can use a for loop and add an if condition but it's too long and there is a simplest way, we will use the filter method
syntax:
var SubArray = ArrayName.filter( function(item){
return //the filtring condition
});
let's apply this to our example
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
//Filtering our array
const filtredList = ShoppingList.filter( function(item){
return item.price <= 5000;
})
console.log(filtredList);
you can try it in your browser and see the result
map()
map() array allows you to create a new array populated with the results of calling a provided function on every element in the calling array.
imagine that there is a promotion of 10% in every item of your shopping list then the price will change, of course, we could change each price using a for loop or simply, we could use the map() methods
var newArray = ArrayName.map(function(item){
//add the modification that you want and return the value
})
in our example, it will look like this
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
//Mapping an array
const NewArray = ShoppingList.map(function(item){
item.price*= 0.9 // we will apply the promotion in each item price
return item // we will return the new element
});
console.log(NewArray);
find()
find() methods allow you to find a specific item inside an array, in our example, we will try to use this function to find the Keyboard item
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
//Find an item in an array
const item = ShoppingList.find(function(item){
return item.name === 'Keyboard';// we aad a condtion of equal
});
console.log(item);
some()
the some() method allows you to test a condition in your array and it return a boolean, so let's imagine that we want to check if there is an item that we will buy more than once then it that's mean if the quantity is higher than 1.
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
//check if we will buy an item more than one time
const check = ShoppingList.some(function(items){
return items.quantity > 1;
});
console.log(check); // it will return true
every()
the method every() is similar to the some() method, except of checking if at least one element confirm the condition every() check that all the items confirm the condition, let's see the same example as before but we will use every() instead of some()
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
//check if we will buy an item more than one time
const check = ShoppingList.every(function(items){
return items.quantity > 1;
});
console.log(check); // it will return false
the result is false because we have some items that we will buy only one time.
reduce()
the reduce method is a little bit different than the other method, it allows you to perform some operation using your array element. to illustrate the utility of this method we will try to use it in a situation. let's suppose that we want to calculate the total sum of our element prices, we can use a for loop but the reduce() method will make the work easier.
var ShoppingList = [
{name:'Computer', price: 9000, quantity:1},
{name:'Mobile Phone', price: 699, quantity:1},
{name:'Earphone', price: 12, quantity:3},
{name:'Keyboard', price: 15, quantity:2},
{name:'Book', price: 2, quantity:10}
];
//Displaying our current Array
console.log(ShoppingList)
const total = ShoppingList.reduce(function(CurrentTotal,items){
return CurrentTotal + items.price;
},0);
console.log(total);
the reduce() method needs two parameters, the first parameter is the reducer function and the second parameter is the starting value. also, the reducer function also needs two parameters that are the current value that we will add to it each item price and the item that represent the array's item
includes()
the includes() method s very simple to use, it checks if an element already exists inside an array and returns a boolean value, for example, let's create a new array of numbers and check if a number exists or not
var numbers = [1,2,3,4,5,6];
var check = numbers.includes(2);
console.log(check); // return true because 2 exist in our array
check = numbers.includes(7);
console.log(check); // return false because 7 does not exist in our array
push()
the push() method allow you to add an element to your array at the last position, let's see a simple example
var numbers = [1,2,3,4,5,6];
console.log(numbers); // it will display: [1,2,3,4,5,6]
numbers.push(7); // it will add 7
console.log(numbers); // it will display: [1,2,3,4,5,6,7]
Thank you guys for following this tutorial, I hope that you enjoyed it.
Most Important javascript Array Methods
Reviewed by Medics
on
April 20, 2020
Rating:
No comments: