Array is a commonly used tool for storing data in a structured collection. There are two different syntaxes for creating arrays in JavaScript:
let arr = new Array("Apple", "Orange", "Banana");
console.log(arr);
[ 'Apple', 'Orange', 'Banana' ]
Don't forget the keyword new
here. This is different from how we created strings using String()
or created numbers with Number()
. Array is not a primitive data type, it is a special kind of object, and new
is how we can create a new instance of an object in JavaScript.
If this doesn't make sense, don't worry, we will get back to this topic after we've discussed objects and the Object-Oriented Programming. For now, you only need to be familiar with the syntax.
The second method to create an array is to use a pair of square brackets, which is also referred to as the array literal:
let arr = ["Apple", "Orange", "Banana"];
console.log(arr);
[ 'Apple', 'Orange', 'Banana' ]
In most cases, the second syntax is used as it is the most convenient.
The elements inside the array can be any data type you want. For example, here is an array with numbers, BigInt
, strings, Boolean values, null
, undefined
, arrays, objects, and even functions:
// prettier-ignore
let arr = [
100, // Number
999999999999999999n, // BigInt
"Qwerty", // String
null, // null
undefined, // undefined
[1, 2, 3], // Array
{ name: "John Doe" }, // Object
function doNothing() { // Function
return null;
},
];
console.log(arr);
[
100,
999999999999999999n,
'Qwerty',
null,
undefined,
[ 1, 2, 3 ],
{ name: 'John Doe' },
[Function: doNothing]
]
Accessing an array element
You can retrieve an array element by specifying its index number.
let arr = [5, 6, 7, 8];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[3]);
5
6
7
8
It is important to note that the index starts from 0
, not 1
, so a[0]
points to the first element, a[1]
points to the second element, and so on.
Alternatively, you can use the at()
method associated with arrays. For instance,
let arr = [5, 6, 7, 8];
console.log(arr.at(0));
console.log(arr.at(1));
console.log(arr.at(2));
console.log(arr.at(3));
The at()
method works the same as the arr[<index>]
syntax, except when you need to retrieve the last item in the array.
Most other programming languages offer what is called the negative indexing, which allows you to retrieve the last item in an array with arr[-1]
, but that is not possible in JavaScript. So for a long time, people's solution was to use the length of the array like this:
let arr = [5, 6, 7, 8];
console.log(arr[arr.length - 1]);
8
arr.length
gives the number of elements in the array, which is 4 in this case. But remember the index starts from 0, so the index of the last item should be arr.length - 1
, which gives 3.
Recently, the at()
method was introduced to offer an easier solution, allowing you to use at(-1)
to access the last item.
let arr = [5, 6, 7, 8];
console.log(arr.at(-1));
8
You can also change an array element using the assignment operator (=
).
let a = [5, 6, 7, 8];
a[1] = 100;
console.log(a);
[ 5, 100, 7, 8 ]
Adding and removing array elements
Besides at()
, there are also methods that enable you to add or remove elements from the array.
pop()
The pop()
method removes the last item from the end of the array.
let arr = ["Apple", "Orange", "Banana"];
arr.pop();
console.log(arr);
[ 'Apple', 'Orange' ]
push()
The push()
method adds new items to the end of the array.
let arr = ["Apple", "Orange", "Banana"];
arr.push("Plum");
console.log(arr);
[ 'Apple', 'Orange', 'Banana', 'Plum' ]
shift()
The shift()
method removes the first element from the beginning of the array, and then shifts all other elements to lower indexes.
let arr = ["Apple", "Orange", "Banana"];
arr.shift();
console.log(arr);
[ 'Orange', 'Banana' ]
unshift()
The unshift()
method moves all elements to higher indexes, and add a new item to the beginning of the array.
let arr = ["Apple", "Orange", "Banana"];
arr.unshift("Plum");
console.log(arr);
[ 'Plum', 'Apple', 'Orange', 'Banana' ]
In practice, the shift()
and unshift()
methods are much slower compared to pop()
and push()
, due to the shifting of the array elements. If possible, you should avoid working at the beginning of the array, and only use pop()
and push()
in your code.
Concatenating arrays
JavaScript also allows you to concatenate multiple arrays together into one array using the concat()
method. For example,
let arr1 = ["Apple", "Orange", "Banana"];
let arr2 = ["Plum", "Peach", "Pear"];
arr1 = arr1.concat(arr2);
console.log(arr1);
[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]
The concat()
method also enables you to join more than two arrays.
let arr1 = ["Apple", "Orange", "Banana"];
let arr2 = ["Plum", "Peach"];
let arr3 = ["Pear"];
arr1 = arr1.concat(arr2, arr3);
console.log(arr1);
[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]
Alternatively, you can use the spread syntax (...
).
let arr1 = ["Apple", "Orange", "Banana"];
let arr2 = ["Plum", "Peach"];
let arr3 = ["Pear"];
let arr = [...arr1, ...arr2, ...arr3];
console.log(arr);
[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]
Searching arrays
-
indexOf()
andlastIndexOf()
Using the indexOf()
method, you can locate the first occurrence of the given item in the array.
let arr = ["Apple", "Orange", "Orange"];
console.log(arr.indexOf("Orange"));
1
Notice that there are two "Orange"
s in this array, but only the location of its first occurrence is returned.
If the element does not exist in the array, the method will return -1
.
let arr = ["Apple", "Orange", "Banana"];
console.log(arr.indexOf("Peach"));
-1
lastIndexOf()
is the opposite of indexOf()
. It returns the location of the last occurrence of the item.
let arr = ["Apple", "Orange", "Orange"];
console.log(arr.lastIndexOf("Orange"));
2
Similarly, if the element does not exist in the array, -1
will be returned.
let arr = ["Apple", "Orange", "Orange"];
console.log(arr.lastIndexOf("Peach"));
-1
find()
find()
is one of the more advanced methods for arrays, as it searches the array based on a test function. If you are new to programming, and have no idea what a function is, you can go through the function lessons first, and then come back to this topic.
let arr = [23, -5, 667, 1, -3, 6, 17, -69];
let answer = arr.find(testFunction);
// This example test function finds the first array element that is greater than 50
function testFunction(value, index, array) {
return value > 50;
}
console.log(answer);
667
The find()
method will pass each item in the array to the test function, and the first element that passes the test will be returned.
The test function should accept three arguments, value
, which corresponds to each element in the array, index
, the index number of that element, and array
, which is the entire array.
You will encounter many more helper functions like this that accept a predefined list of arguments, and some of them might be difficult to understand. In this case, you could print them out into the console using console.log()
. This would help you understand what they are, and what you can do with them.
let arr = [23, -5, 667, 1, -3, 6, 17, -69];
let answer = arr.find(testFunction);
// This example test function finds the first array element that is greater than 50
function testFunction(value, index, array) {
console.log(`Value: ${value}`);
console.log(`Index: ${index}`);
console.log(`Array: ${array}`);
console.log("\n");
return value > 50;
}
console.log(answer);
Value: 23
Index: 0
Array: 23,-5,667,1,-3,6,17,-69
Value: -5
Index: 1
Array: 23,-5,667,1,-3,6,17,-69
Value: 667
Index: 2
Array: 23,-5,667,1,-3,6,17,-69
filter()
The filter()
method is similar to find()
, except instead of returning a single value that passes the test, filter()
returns an array of values.
let arr = [23, -5, 667, 150, -3, 60, 17, -69];
let answer = arr.filter(testFunction);
function testFunction(value, index, array) {
return value > 50;
}
console.log(answer);
[ 667, 150, 60 ]
every()
The every()
method iterates over the entire array, and examines if the element passes a test. If all element passes, every()
returns true
, and if not, every()
returns false
.
let arr = [1, 2, 3, 4, 5];
let answer = arr.every(testFunction);
// Check if all elements are greater than 0
function testFunction(value, index, array) {
return value > 0;
}
console.log(answer);
true
includes()
The includes()
method tests if a given value exists in the array.
let arr = [1, 2, 3, 4, 5];
let answer = arr.includes(100);
console.log(answer);
false
You can also provide an index, which tells the includes()
method to check if the value exists at the exact index.
let arr = [100, 2, 3, 4, 5];
let answer = arr.includes(100, 2);
console.log(answer);
false
Notice that even though 100
exists in the array, it does not exist at the index 2
, so the method returns false
.
Sorting arrays
JavaScript offers four different methods that allow you to sort the array, sort()
, toSorted()
, reverse()
, and toReversed()
.
Sorting strings
By default, these methods are used to sort arrays with string values.
-
sort()
will sort the array alphabetically.
let arr = ["Apple", "Orange", "Banana"];
arr.sort();
console.log(arr);
[ 'Apple', 'Banana', 'Orange' ]
-
reverse()
will reverse the array.
let arr = ["Apple", "Orange", "Banana"];
arr.reverse();
console.log(arr);
[ 'Banana', 'Orange', 'Apple' ]
-
toSorted()
is just likesort()
, except it returns the sorted result without altering the original array.
let arr = ["Apple", "Orange", "Banana"];
let sortedArr = arr.toSorted();
console.log(sortedArr);
console.log(arr);
[ 'Apple', 'Banana', 'Orange' ]
[ 'Apple', 'Orange', 'Banana' ]
-
toReversed()
method is just likereverse()
, except it returns the sorted result without altering the original array.
let arr = ["Apple", "Orange", "Banana"];
let sortedArr = arr.toReversed();
console.log(sortedArr);
console.log(arr);
[ 'Banana', 'Orange', 'Apple' ]
[ 'Apple', 'Orange', 'Banana' ]
Sorting numbers
The sort()
method can also be used to sort numbers, but it requires a bit more customization. Because by default, these methods will convert the numbers into strings, and then sort them alphabetically, which would give results like this:
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
console.log(arr.toSorted());
[ -1, 17, 2, 20, 21, 3, 45, 9 ]
To sort numbers, you must pass a compare function.
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
arr.sort(compareFunction);
function compareFunction(a, b) {
return a - b;
}
console.log(arr);
[ -1, 2, 3, 9, 17, 20, 21, 45 ]
The compare function takes two input values, a
and b
, and return either a positive value, a negative value, or 0. The function compares all the values in the array, two numbers at a time.
- If the function returns positive,
b
will be placed beforea
. - If the function returns negative,
a
will be placed beforeb
. - If the function returns 0, no changes will be made.
This example sort the array in a ascending order. To sort in the descending order, simply make the compare function return b - a
.
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
arr.sort(compareFunction);
function compareFunction(a, b) {
return b - a;
}
console.log(arr);
[ 45, 21, 20, 17, 9, 3, 2, -1 ]
Iterating over an array
Another operation we often perform on arrays is iterating over all of its values. The most straightforward way to do this is with a loop. If you don't know what a loop is, please go through the linked lesson first.
Using loops
Take a look at this example:
for (let i = 0; i < a.length; i++) {
. . .
}
let i = 0
initiates the variable i
which will be the index number of each array element. The index i
starts from 0. i
will increment by 1 for every iteration (i++
, which is a shorthand for i = i + 1
), until it reaches a.length
.
a.length
is the length of the array, which means the loop will terminate when i
equals a.length - 1
. Because for the next iteration, i
will become a.length
, which violates the condition i < a.length
.
Besides using the index, you can also access each array element with a for of
loop, which looks like this:
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
for (let ele of arr) {
console.log(ele);
}
2
-1
45
3
21
17
9
20
Using methods
There are also two built-in methods in JavaScript that allow you to iterate over the array without having to use a loop. This is one of the greatest features in JavaScript, because for most other programming languages, you will have to create the loop your self.
The first method is forEach()
. Here is an example of calculating the sum of all array elements using the forEach()
method.
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
let sum = 0;
arr.forEach(calcSum);
function calcSum(value, index, array) {
sum = sum + value;
}
console.log(sum);
116
If you would like to perform some actions to each array element, and then return the transformed result, use the map()
method. For example, here we are using map()
to return an array whose elements are the square of the original value.
let arr = [2, -1, 45, 3, 21, 17, 9, 20];
let sum = 0;
let squared = arr.map(calcSum);
function calcSum(value, index, array) {
return value ** 2;
}
console.log(squared);
console.log(arr);
[ 4, 1, 2025, 9, 441, 289, 81, 400 ]
[ 2, -1, 45, 3, 21, 17, 9, 20 ]
The map()
method will return a new array with the transformed elements, and the original will not be changed.
Matrix
Matrix is a concept that exists in both mathematics and computer science. It is defined as a two dimensional array with its elements arranged in rows and columns like this:
It is possible for you to create such a structure using JavaScript by putting several smaller arrays inside a bigger array.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
To retrieve an element from this matrix, you need to specify two indexes, matrix[<row>][<col>]
.
console.log(matrix[0][1]); // -> 2
console.log(matrix[1][0]); // -> 4
console.log(matrix[2][2]); // -> 9
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.