How to Create and Use Arrays in JavaScript
Being able to use arrays in JavaScript is vital since it is one of the best ways to manage data. Fortunately using arrays is pretty straightforward in JavaScript.
In this guide, we will cover the most common ways to use an array in JavaScript. Starting with how to create an array and then how to manipulate, add and remove data in it.
Creating an Array in JavaScript
To create an array in JavaScript, type []
(opening and closing square brackets.)
var arry = ['a','b','c'];
In the above example, we are creating an array containing three strings of data; a
b
and c
and setting it as the variable arry
so it can be used later in the code.
The square brackets are shorthand for the new Array()
utility in JavaScript. You should always use []
as it is cleaner and makes your code more readable. If you want to use new Array
there is an example below.
var arry = new Array('a','b','c');
Accessing Data in an Array
Items in JavaScript arrays are stored in numerical key values, which by default start at 0
. To access an item in the array we can use the array variable followed by square brackets containing the key number.
var a = arry[0];
In the above example, we are getting the first element of the array we previously-stored as arry
and setting it as the variable a
.
Updating Items in an Array
To update an array we can call the array key in our array variable by using []
(square brackets) and then setting it to a value using =
(equals).
arry[0] = 'd';
['d','b','c']
In the above example, we are setting the first value in the arry
array to the string d
.
Using Objects in an Array
To use objects in a JS array we just have to wrap them in {}
(braces) and name the properties within. The syntax works like this:
{ propName: 'content', propName: 'content', propName: 'content' },
Here is a real-world example of objects in an array:
var item_array = [
{ name: 'foo', content: 'some text', url: 'slug' },
{ name: 'foo', content: 'some text', url: 'slug' }
];
We can access objects in the above array by using the key name inside []
(square brackets), then a .
(dot) followed by the property name.
document.getElementById("name").textContent = item_array[0].name;
foo
In the above example, we are getting the name
property of the object located at key 0
of the item_array
and then setting the text content of a div
with an ID of “name”.
Count the Number of Items in an Array
To count the number of items in an array we can use the JavaScript length
utility. This will give us the total count of all the items (not the highest key number, which would be one less than the total items since counting starts at 0
.)
var arry = ['a','b','c','d'];
var count = arry.length;
document.getElementById("name").textContent = count;
4
In the above example, I am setting an imaginary div
with the ID of “name” to the value of count. You can, of course, use count
for whatever you need.
Sorting Arrays
To sort the data of an array in alphabetical order we can use the sort
JavaScript utility. To use it, pass the array variable name followed immediately by .sort()
.
var arry = ['d','c','b','a'];
var sorted = arry.sort();
['a','b','c','d']
The important thing to note when using .sort()
is that the original array gets sorted. In the above example, the sorted
variable is a little redundant, though depending on the situation it may be what you want.
Looping Through an Array
There are a number of ways to loop through a JavaScript array. The most simple and efficient is by using a for
loop. Let's loop through all the items in our array and access the content of each item by using the i
variable.
for (var i = 0; i < arry.length; i++) {
arry[i]
}
for
takes three parameters, the starting iteration (index) number, the logic to decide when to stop looping and the incrementation/decrementation of the index number.
for (var index = 0; index = 10; index++)
If you need to decrement the index
you can use --
(two minuses).
Another approach to looping through an array is to use the forEach
Javascript utility. This will go through every item in the array. To use it we can call our array variable followed by .forEach()
.
arry.forEach(myFunction)
function myFunction(value, index, array) {
// do something here
}
In the above example, we are calling a function called myFunction
, which will be used to do something with each array key iteration. The optional parameters that are passed into myFunction
are supplied by the forEach
utility and are as follows:
value
the content of the array itemindex
the key number of the current iterationarray
the full array should you need it
Get the last Element
Getting the last element can be done by getting the length of the array and getting the item by its key.
arry[arry.length -1];
The reason why -1
is added is because length
supplies the real number of items and we are accessing the array by key, which will always be one less.
Push New Items to an Array
To add an item to an existing array in JavaScript we can use the push
utility. push
will add a new item to the end of the array and not modify the rest of the array. To use it we will pass .push()
at the end of the array variable and pass the content we wish to add inside ()
(brackets).
var arry = ['a','b','c','d'];
arry.push('e');
['a','b','c','d','e']
Add Items to Array Starting at an Index
Sometimes we may need to add an item at a specific key. To do this we can use the splice
utility. Like the previous utilities we talked about, splice
is used by passing it in after the array variable using a .
(dot).
Firstly let's analyse the syntax of splice and what its parameters do.
arry.splice(index, howmanytoremove, item1, item2)
index
- the key in the array we wish to add an item tohowmanytoremove
- remove existing items as they are added up to this number. If you just want to add items and keep all existing items in the array set this value to0
.item1
etc… - the list of items to add
var arry = ['a','b','c','d'];
arry.splice(1, 0, 'x', 'y');
['a', 'x', 'y', 'b', 'c', 'd']
In the above example, we are adding two items with the content of x
and y
to the array and keeping all existing array items intact.
Note - remember that splice
is based on array keys meaning the key will be one less than the actual number entered.
Remove Items From an Array by Key
To remove items from an array based on its key we can use splice
.
var arry = ['a','b','c','d'];
arry.splice(1, 1);
['a','c','d']
The trick here is to tell splice
to remove one item and not supply any new items to add, resulting in just an item getting removed at the specified key.
Remove Item from the Beginning of an Array
Removing an item from the beginning of an array can be done using the JavaScript shift
utility.
var arry = ['a','b','c','d'];
arry.shift();
['b','c','d']
As you can see the a
item at key 0
has been removed and all the other items have been shifted up.
Remove Item from the End of an Array
To remove an item from the end of the array use the JavaScript pop
utility.
var arry = ['a','b','c','d'];
arry.pop();
['a','b','c']
Filter Array
If we need to remove items from an array that don't match certain criteria we can use the JavaScript filter
utility. To use it pass it in at the end of an array variable using .
(dot) and then pass a function as the first argument.
var ages = ['45','18','16','25','32','14'];
var pass = ages.filter(function(age) {
return age >= 18;
});
["45", "18", "25", "32"]
The above example shows how we can make a function to filter out numbers that are less than 18.
Find Items
To return only the first match from an array, use the JavaScript find
utility. It works just like the filter
utility except it will only output the content of the first match from the array.
var ages = ['45','18','16','25','32','14'];
var pass = ages.find(function(age) {
return age >= 18;
});
45
The first number in the ages
array that is 18
or above is 45
at key 0
which is indeed what filter
outputs.
Check if a Variable is an Array or an Object
Sometimes we need to know whether a variable is an array or an object. The easiest way to check this is by using the Array.isArray
utility which returns true
or false
.
var arry = ['a','b','c','d'];
function function_name(arry) {
return Array.isArray(arry);
}
console.log(function_name(arry));
true
The above example shows how we might write a function to check whether an array is an array.
Check if an Array is Empty
Sometimes we may need to verify whether an array is empty or not. This can be done by using some if
logic to determine if the array has a length greater than 0
.
var arry = [];
function is_empty(arry) {
if (!arry.length) {
return true;
} else {
return false;
}
}
console.log(is_empty(arry));
true
The above example says if the length of the array is not equal to 0
(false) return true
else return false
.
Conclusion
You now know how to set up a JavaScript array and manipulate its content in a variety of different ways.