Arrays are superheroes when it comes to organizing data. This article explains how they function, why they're essential for anyone looking to properly manage data and how to effectively manipulate it.
Overview :
- What is an array?
- Initializing an array
- length property
- Accessing and changing array elements
- Multi-dimensional array
- Array Methods
What is an array?
Think of an array as a multi-drawer cabinet. Each drawer in that cabinet has a different item in it. You can reach an item by simply opening the drawer that has the item you want.
Similarly an array is a variable that can store multiple values.
Initializing an array
We've previously seen how to Initialize a variable.
let name = "John";
Array literal
Initializing an array is similar to initializing a variable with some differences. While a variable can store a single data type as we've seen in the example above, an array can hold multiple values of different data types. You declare an array using square brackets.
const food = [];
You can pass multiple values of different data types to the square brackets to initialize the array.
const values = ["ice cream", 57, "biscuit", true, 3.14];
New Keyword
You can also declare and assign values to an array using the new
keyword.
const values = new Array();
const elements = new Array("one", 2, true, 3.14);
These two methods do exactly the same thing, but use the array literal method for efficiency, readability, and speed.
Length Property
In the previous article How to make the most out of strings We've seen what the length
property does. Let's go over it one more time.
The length property returns the size of the array or the number of items in the array.
const values = ["ice cream", 57, "biscuit", true, 3.14];
console.log(values.length); //5
Accessing and changing array elements
The position of an item in an array is known as an index. We start counting the items of an array from zero. This is known as zero-based indexing.
const values = ["ice cream", 57, "biscuit", true, 3.14];
let index0 = values[0];
console.log(index0); //ice cream
Let's change an item in the values
array
const values = ["ice cream", 57, "biscuit", true, 3.14];
values[1] = 26;
console.log(values);
//[ 'ice cream', 26, 'biscuit', true, 3.14 ]
As we can see the number 57 was modified to 26.
The length property always starts counting from 1. It's always 1 number higher than than the index
You can access array elements using the length property. For example, let's access the last item and second to last item of the values
array.
const values = ["ice cream", 57, "biscuit", true, 3.14];
console.log(values[values.length-1]); //3.14
console.log(values[values.length-2]); //true
So what's happening in the example? Let's break it down.
We've previously accessed the first element of the array using this notation values[0]
which gave us ice cream
.
values[values.length-1]
here is values[5 - 1]
which is value[4]
which will give us 3.14
.
Why are we using -1
?
As we've previously stated arrays use zero-based indexing. if we try to get the value at value[5]
we will get undefined
which means that there's no value assigned to the index 5 since we start counting from zero. Counting from 0
to 4
gives us five values which is the length of the array.
const values = ["ice cream", 57, "biscuit", true, 3.14];
console.log(values[values.length]); //undeifned
Multi-dimensional array
Now that we have a strong understanding of what an array is, let's explain what a multi-dimensional array is.
A multi-dimensional array is an array that contains other arrays.
const multiDimensional = [
[2, "cat", false],
[3.14, true, "mango"],
["peach", 32, true]
];
Multi-dimensional arrays can be accessed in the same way as an array by using bracket notation. Take our multiDimensional
array which has 1 outer layer
which is the entire array.
const multiDimensional = [
[2, "cat", false],
[3.14, true, "mango"],
["peach", 32, true]
];
console.log(multiDimensional[0]); //[2, "cat", false]
console.log(multiDimensional[1]); //[3.14, true, "mango"]
console.log(multiDimensional[2]); //["peach", 32, true]
The inner layer
consists of 3 inner layers
which are the 3 arrays. The items (values) within each inner array belong to the inner layer.
Let's say we want to access the value mango
in our example:
const multiDimensional = [
[2, "cat", false],
[3.14, true, "mango"],
["peach", 32, true]
];
console.log(multiDimensional[1][2]);//mango
Our value mango
is the second array in multiDimensional
, so it's in position 1 (remember zero-based indexing). The mango
value is the last item in that array meaning at position 2.
Array methods
Array operations like insertion, deletion, searching, and transformation can be performed on an array's elements using array methods. These methods make writing custom code less difficult and create more readable, compact and useful code.
Method | Description |
---|---|
push() |
Adds one or more elements to the end of an array. |
unshift() |
Adds one or more elements to the beginning of an array. |
splice() |
Adds or removes elements from an array at a specified index. |
pop() |
Removes the last element from the end of an array and returns it. |
shift() |
Removes the first element from the beginning of an array and returns it. |
map() |
Creates a new array by applying a function to each element of the array. |
filter() |
Creates a new array with elements that pass a certain condition. |
reverse() |
Reverses the order of elements in an array. |
sort() |
Sorts the elements of an array in place or based on a provided function. |
copyWithin() |
Copies elements within an array to a specified destination. |
indexOf() |
Returns the first index at which a given element can be found in the array. |
lastIndexOf() |
Returns the last index at which a given element can be found in the array. |
includes() |
Checks if an array includes a certain element, returning a boolean. |
find() |
Returns the first element in the array that satisfies a given condition. |
findIndex() |
Returns the index of the first element that satisfies a given condition. |
join() |
Joins all elements of an array into a string using a specified separator. |
toString() |
Converts an array to a string representation. |
concat() |
Combines two or more arrays, returning a new concatenated array. |
Spread Operator (... ) |
Expands an array into individual elements. |
slice() |
Returns a shallow copy of a portion of an array into a new array. |
reduce() |
Applies a function against an accumulator and each element in the array, reducing it to a single value. |
Add methods
We can add an element to an array using multiple methods.
- Using indexing
const values = [2, "cat", false]
values[3] ="miami";
console.log(values); //[2, "cat", false, "miami"]
- Using length property
const values = [2, "cat", false]
values[values.length] ="miami";
console.log(values); //[2, "cat", false, "miami"]
Using these methods is not recommended because it can create undefined "holes" in an array.
const values = [];
values[2] = 'Hello';
console.log(values); // Output: [ , , 'Hello' ]
console.log(values.length); // Output: 3
console.log(values[0]); // Output: undefined
console.log(values[1]); // Output: undefined
console.log(values[2]); // Output: 'Hello'
Category | Array Methods |
---|---|
Element Insertion |
push() , unshift() , splice()
|
- push()
The push()
method alters the array by adding a single or more values to the end of it and returns the new length
of the altered array.
const numbers = [1, 2, 3];
const newLength = numbers.push(4, 5);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(newLength); // Output: 5
- unshift()
The unshift()
method is used to add a single or multiple values to the beginning of the array and returns its new length
.
const numbers = [3, 4, 5];
const newLength = numbers.unshift(1, 2);
console.log(numbers); // Output: [1, 2, 3, 4, 5]
console.log(newLength); // Output: 5
- splice()
The splice()
method is used to add remove or replace values at a specified index.
Here's an example of using splice to add and remove elements:
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'melon', 'cherry');
console.log(fruits);
// Output: ['apple', 'melon', 'cherry', 'grape']
console.log(removedFruits);
// Output: ['banana', 'orange'] (removed elements)
Remove methods
Category | Array Methods |
---|---|
Element Deletion |
pop() , shift() , splice()
|
- delete()
const values = ["apple", true, 2, "Mango"];
delete values[1];
console.log(values); //['apple', <1 empty item>, 2, 'Mango']
console.log(values.length);//4
It is not recommended to remove an item from an array using the delete()
method because the original array length remains unchanged because it only removes the value from the array without freeing up that index. Meaning the length of the array stays the same.
- pop()
The pop()
method alters the array by removing the last element from the array and returns the removed value.
const numbers = [1, 2, 3, 4, 5];
const removedElement = numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4]
console.log(removedElement); // Output: 5 (last element)
- shift()
The shift()
method alters the array by removing the first element of it and returns the removed value.
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruit = fruits.shift();
console.log(fruits); // Output: ['banana', 'orange', 'grape']
console.log(removedFruit); // Output: 'apple' (first element)
Transform methods
Category | Array Methods |
---|---|
Element Transformation |
map() , filter() , reverse() , reduce() ,sort() , copyWithin()
|
The map()
, filter()
, and reduce()
methods are higher order functions
which we'll discuss in an upcoming article. All you have to know for now is that they're array methods do not modify the original array but return a new modified array.
- reverse()
The reverse()
method alters the original array and reverses the order of its values.
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1] (original array is reversed)
- sort()
The sort()
method alters the original array and sorts its values in ascending order.
const fruits = ['banana', 'apple', 'grape', 'orange'];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'grape', 'orange'] (sorted alphabetically)
//sorting numbers
const numbers = [4, 2, 8, 6, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // Output: [1, 2, 4, 6, 8] (sorted numerically)
When sorting numbers in ascending order, the expression a - b
is frequently used as a comparison function. This method makes use of the sort() method's behavior, which assumes the comparison function that returns a negative, zero, or positive value to determine the order of elements.
Why a - b
?
- If
a - b
returnsa
negative value, it indicates thata
should come beforeb
in the sorted order. - If
a - b
returns zero, it indicates thata
and b are considered equal in terms of sorting order. - If
a - b
returnsa
positive value, it indicates thata
should come afterb
in the sorted order.
- copyWithin()
The copyWithin()
method does not modify the array and copies a piece of it to another place in the array.
it takes 3 parameters:
-
target
: which is where the elements you're copying will be placed. -
start
: which is from where this method will start copying the elements in the array. -
end
: Which is the index prior to which copies of elements should stop. It takes the array's length as a default if omitted.
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);
console.log(numbers); // Output: [4, 5, 3, 4, 5]
Search methods
Category | Array Methods |
---|---|
Element Search |
indexOf() , lastIndexOf() , includes() , find() , findIndex()
|
- indexOf()
The indexOf()
method returns the index of the element you're trying to find and -1
if it was not found.
const fruits = ['apple', 'banana', 'orange', 'apple'];
const index = fruits.indexOf('apple');
console.log(index); // Output: 0 (index of the first 'apple')
- lastIndexOf()
The lastIndexOf()
method returns the index of last occurrence of the element you're trying to find and -1
if it was not found.
const fruits = ['apple', 'banana', 'orange', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');
console.log(lastIndex); // Output: 3 (index of the last 'apple')
- includes()
The includes()
method indicates if an element is present in an array. It returns true
if the element is in the array and false
if it is not.
const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.includes('banana');
console.log(hasBanana); // Output: true (array includes 'banana')
find and findIndex methods are both higher order functions which we will discuss in a later article.
Conversion methods
Category | Array Methods |
---|---|
Element Conversion |
join() , toString()
|
- join()
The join()
method creates a string using the argument passed as a separator.
const fruits = ['apple', 'banana', 'orange'];
const joinedString = fruits.join(', ');
console.log(joinedString); // Output: "apple, banana, orange"
- toString()
The toString()
method converts the array into a string separated by comas.
const numbers = [1, 2, 3, 4, 5];
const numbersString = numbers.toString();
console.log(numbersString); // Output: "1,2,3,4,5"
Copy methods
Category | Array Methods |
---|---|
Copying |
concat() , Spread Operator (... ), slice()
|
- concat()
The concat()
method joins two or more arrays together and returns a new array.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = array1.concat(array2);
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
- The spread operator
(...)
This operator is used to expand element of an array and can be used to combine arrays.
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];
console.log(combinedArray); // Output: [1, 2, 3, 4, 5, 6]
- slice()
The slice()
method is used to create a copy of a portion of an array and returns a new array.
const numbers = [1, 2, 3, 4, 5];
const copiedNumbers = numbers.slice(1, 4);
console.log(copiedNumbers); // Output: [2, 3, 4]
Top comments (2)
Thank you for this explanation. I am relatively new to the world of coding, but I have quickly seen the importance of Arrays. The usefulness of storing different types of data into a single variable has been so helpful!
Thank you for the built in methods as well, some of these are going to be so useful going forward.
Best,
Daniel Todd
Hey Daniel! i am happy to hear that you've found my explanation clear and useful! If you find yourself having a question feel free to leave it in a comment and i will try my best to provide you with the help you need!
-Jo