Introduction
Arrays in JavaScript are fundamental data structures that efficiently store and manipulate collections of values. JavaScript arrays come with a wide range of built-in methods, which enable web developers to perform tasks on array elements with ease.
In this guide, we will delve deep into these array methods in JavaScript. I aim to simplify each method and illustrate its usage with code examples. Whether you're a beginner looking to grasp the basics of arrays in JavaScript or an intermediate developer seeking to enhance your knowledge, this guide will teach you the best use cases for each array method in your JavaScript projects.
By the end of this guide, you'll have acquired the skills to perform straightforward array manipulations, enhancing the efficiency and readability of your code. We'll cover everything from understanding what an array is to creating, accessing, modifying, iterating over, and testing its elements. Each section provides a comprehensive explanation and includes code samples as needed.
With that said, let's dive right in.
What Is a JavaScript Array?
A JavaScript array is a single variable that is used to store elements of different data types (strings, numbers, booleans, etc.).
Arrays help you group multiple values under a single name and access them by their index number. It's important to note that, in JavaScript and many programming languages, array indexing typically begins at 0, making it a zero-indexed data structure.
What are JavaScript array methods?
JavaScript array methods are pre-defined functions in the JavaScript language that enable us to easily modify and manipulate arrays. These methods are a fundamental aspect of JavaScript arrays, offering a wide range of tools for efficiently performing tasks like transformations and calculations on arrays, saving you from the need to write these operations from scratch.
How to Create Arrays in JavaScript
The simplest and most frequently used method for declaring and initializing arrays in JavaScript is by employing square brackets, also known as array literals.
Look at an example:
// Creating an array of numbers, strings and boolean using square brackets
const personalData= [1, "Chris", 3, "python", 5, true];
An alternative method for creating an array involves utilizing the pre-existing Array constructor, in which you provide the initial elements of the array as arguments.
Here's an example:
// Creating an array of numbers, strings and boolean using the Array constructor
const personalData= new Array(1, 'Chris', 3, 'python', 5, true);
I recommend sticking with square brackets when writing code because it helps you write clear and readable code. Additionally, using square brackets can improve performance, particularly when dealing with large arrays.
If you opt to use the array constructor for any reason, make sure to include the new
keyword. This is essential for creating instances of objects, including arrays. So, whenever you use the Array constructor to create an array, remember to include the new
keyword.
Accessing Array Elements
To access elements within an array, there are several methods available. Let's explore the primary one:
Indexing
Indexing involves assigning a numerical value to each item in a data structure, enabling direct access to array elements. You can achieve this by using square brackets [] and specifying the index of the desired element.
Here's the syntax: const element = array[index]
;
As mentioned earlier, it's important to note that array indices start at 0, meaning the first element is at index 0, the second element is at index 1, and so forth.
Look at an example:
const numArray = [10, 20, 30, 40, 50];
// Access the element at index 2 (i.e the third element)
const age = myArray[2];
console.log(age); // Result: 30
In addition, you can change an array element using the index, as in the example below:
const numArray = [10, 20, 30, 40, 50];
// Modify the element at index 3 (fourth element)
numArray[3] = 45;
console.log(numArray); // Output: [10, 20, 30, 45, 50]
Getting an Array Length
If you want to get the length of elements in an array, you can do that using the length
property.
Using the same numArray
above, here's an example:
const numArray= [10, 20, 30, 40, 50];
// Get the length of the array
const arrayLength = numArray.length;
console.log(`The array has ${arrayLength} elements.`);
// Output: The array has 5 elements.
Another thing we can do with the length
property is to find the last element of an array. Look at an example:
const numArray = [10, 20, 30, 40, 50];
// Access the last element using length - 1
const lastIndex = numArray.length - 1;
const lastElement = numArray[lastIndex];
console.log(lastElement); // Output: 50
Task 1: Find out how you can retrieve the first element of the above array. Send me a screenshot of your code in my DM on Twitter.
There's no limit to what you can do with each of the methods of retrieving elements from arrays. Spend some time and find out more about what is possible.
Modifying Arrays
Some array methods are specifically used to make changes, such as adding or removing elements from an array from either the end or beginning, adding or removing elements at specified positions, or generally making updates to the array data structure. Let's look at the most frequently used ones.
Add Elements to an Array
There are three main ways to add elements to an array:
Using the push
method:
This helps you add one or more elements to the end of an array and return the new length of the array.
const myFriends= ['Goodness', 'Chiamaka'];
myFriends.push('Gideon', 'Deborah');
console.log(myFriend); // ['Goodness', 'Chiamaka', 'Gideon', 'Deborah']
Using the unshift
method:
The unshift
method allows you to add one or more elements to the beginning of an array and returns the new length of the array.
Here's a good example:
const myFriends= ['Goodness', 'Chiamaka', 'Gideon'];
myFriends.unshift('Obinna', 'Charis');
console.log(myFriend); // ['Obinna', 'Charis', 'Goodness', 'Chiamaka', 'Gideon']
Using the splice
method:
The power of the splice
method lies in its ability to perform the dual functions of the push
and unshift
methods.
In particular, it helps you add or remove elements from an array at specific positions or even replace them.
To help you understand it better, I'll provide you with the syntax and explain how it works before showing you an example with a code snippet.
Let's go.
Adding Elements with Splice
The syntax: array.splice(startIndex, 0, element1, element2, ...);
Here's how it works:
startIndex
: The index at which to start adding elements to the array.0
: Specifies that none of the elements should be removed.element1, element2, ...
: The elements you want to add to the array.
Example:
const testScores = [65, 72, 54, 85];
testScores.splice(2, 0, 93); // Insert 93 at index 2
console.log(testScores); // [65, 72, 93, 54, 85]
You can see, it is quite simple and straightforward.
Removing Elements with Splice
The syntax: array.splice(startIndex, numberOfItemsToRemove);
How it works:
startIndex
: The index at which to start removing elements.numberOfItemsToRemove
: The number of items (elements) to remove from the array.
Here's an example:
const myFriends= ['Goodness', 'Chiamaka', 'Gideon', 'Chris'];
myFriends.splice(1, 2); // Remove 2 elements starting at index 1
console.log(myFriends); // ['Goodness', 'Chris']
Replacing Elements with Splice:
The syntax: array.splice(startIndex, numberOfItemsToRemove, newItem1, newItem2, ...);
How it works:
startIndex
: The index at which to start replacing elements.numberOfItemsToRemove
: The number of elements to remove from the array.newItem1, newItem2, ...
: The elements to insert as replacements.
Let's look at a good example using myFriends
array above:
const myFriends= ['Goodness', 'Chiamaka', 'Gideon', 'Chris'];
myFriends.splice(3, 2, 'Philemon'); // Replace the element at index 3 with 'Philemon'
console.log(myFriends); // ['Goodness', 'Chiamaka', 'Philemon', 'Chris']
Like in other array methods, there are several changes you can make in an array using unshift
,push
and splice
methods.
Task 2: How do you add and replace elements in an array simultaneously? I'd be glad to see your code screenshot and make corrections where necessary. Reach out to me via my DM on Twitter.
Removing Elements to an Array
I have already shown you how you can use the splice
method to add or remove elements from an array from any specific position.
I want to now show you just as in the use of the push
and unshift
methods to add elements, how you can remove elements from an array either from the start or at the end of an array.
pop
Method:
The pop
method removes the last element from an array and returns the new length of the array.
Here's a simple example:
const favouriteFruits = ['apple', 'banana', 'cherry', 'orange', 'guava'];
favouriteFruits.pop(); // Removes 'guava' and returns it
console.log(favouriteFruits); //Output: ['apple', 'banana', 'cherry', 'orange']
shift
Method:
The shift
method simply does the opposite of the pop
method by removing the first element from an array and returns the new length of the array.
Look at an example:
const favouriteFruits = ['apple', 'banana', 'cherry', 'orange', 'guava'];
favouriteFruits.shift(); // Removes 'apple' and returns it
console.log(favouriteFruits); //Output: ['banana', 'cherry', 'orange', 'guava']
You're familiar with the slice
method. You go through it again to better understand how to use it to remove elements from an array.
Methods for Iterating Over Arrays
Iteration is the process of going through something one by one or in a step-wise process.
There are various processes for iterating over arrays in JavaScript.
The method you choose at a given time is dependent on the way you write your code and/or on the specific requirements for your projects. As usual, let's look at the most commonly used methods for iterating over arrays.
Let's go.
forEach
method:
The forEach
method unlike the for
loop lets you iterate over the elements of an array and perform a specified action for each element. It also provides a much more concise and readable way to iterate over an array compared to a traditional for
loop.
Look at the syntax:
array.forEach(function(currentValue, index, array) {
// Code to be executed for each element in the array
});
Here's how this method works:
currentValue
is the current element being processed in the array.index
is the index of the current element.array
is the array thatforEach
is being called on.
You perform any operations you need on the current element inside the callback function.
If you're wondering what a callback function is, you can read this on w3schools.
Here's an example of how to use forEach
in an array:
const favFruits = ['apple', 'banana', 'pineapple', 'orange'];
favFruits.forEach(function(fruit, index) {
console.log(`Fruit at index ${index}: ${fruit}`);
});
// This is what will be logged out:
/*
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: pineapple
Fruit at index 3: orange
*/
You can also use arrow functions and add up to three parameters to the function.
favFruits.forEach((fruit, index) => {
console.log(`Fruit at index ${index}: ${fruit}`);
});
forEach
is especially useful when you want to perform an action on each element of an array without the need to manually manage the loop counter and length, as you would with a for
loop. It's a clean and readable way to work with arrays and is a preferred choice in many situations when dealing with array iterations in JavaScript.
.map()
array:
The map
method helps you loop through an array and change its elements using a callback function. It lets you create a new array by applying a given function to each element of the original array.
Like the forEach
, the syntax for .map() is:
const newArray = originalArray.map(function(currentValue, index, array) {
// Code to transform the current element
// The result is added to the new array
return transformedValue;
});
Similarly, you can perform any operations you need on the current element inside the callback function.
Let's see an example:
const age = [15, 24, 30, 34, 45];
const doubledAge = age.map(function(number) {
return number * 2;
});
console.log(doubledAge); // Output: [15, 24, 30, 34, 45]
In the above code, doubledAge
is the new array mapped from the original age
array.
The map
method is very useful for creating a new array based on the transformation of the original array's elements. It's the best way to loop through arrays, especially where you need to transform data in an array without modifying the original array, like in the example above.
There are other methods (filter() and reduce()) for iterating over an array. Bhavesh Rawat has an article on How to Use filter() and reduce() in JavaScript.
Searching and Sorting Arrays
These are methods used for checking if a particular element is present in an array, what position it is, and sometimes to rearrange the elements in the array. Let's look at the most used methods.
indexOf()
method:
The indexOf()
is usually used to check if an element exists in an array and find its position. The indexOf()
method searches for the particular element in the array and returns its index if it is present. If the element is not found, it returns -1.
The syntax: array.indexOf(searchElement, fromIndex)
Let's look at an example:
const favFruits = ['apple', 'banana', 'cherry', 'pineapple', 'orange'];
const index = favFruits.indexOf('banana');
console.log(index); // Output: 1 (banana is at index 1)
DIY: Check what the result would be for a fruit that is absent in the array.
.includes()
method:
The includes()
method helps you check if a particular element exists in an array. So, you only use it when you need to check if an element is present or absent in an array. If present, it returns the Boolean true
. Otherwise, it outputs false
.
The syntax: array.indexOf(searchElement, fromIndex)
const favFruits = ['apple', 'banana', 'cherry', 'pineapple', 'orange'];
const hasGuava= favFruits.includes('guava');
console.log(hasGuava); // Output: false (guava is not found in the array)
sort()
method:
The sort()
method is handy when you want to sort an array alphabetically or numerically.
Here's the syntax:array.sort([elementsToBeSorted])
Please note that by default, the sort()
method in JavaScript sorts elements as strings.
Let's see an example:
const age = [10, 5, 20, 1, 15];
age.sort();
console.log(age); // Output: [1, 10, 15, 20, 5]
Observe that the array is sorted as if the ages were strings. This happens because JavaScript converts the ages (which are numeric values) to strings and then compares their Unicode values. In this case, '1' comes before '10' because '1' has a lower Unicode value.
To solve this problem, it's often wise to provide a custom function to the sort() method.
Here's what I mean:
const age = [10, 5, 20, 1, 15];
age.sort(function(a, b) {
return a - b;
});
console.log(age); // Output: [1, 5, 10, 15, 20]
The function in the above example tells JavaScript to sort the numbers in ascending order. You can adjust themcustomFunction
to sort in descending order or based on any other criteria you want.
concat()
method:
The function of the concat()
method derives from the root word concatenate, which means "to link things together in a chain or series".
The concat()
method is used to join two or more arrays into a new array. The concat()
method does not change the elements of the original array.
The syntax is:const newArray = firstArray.concat(secondArray, thirdArray, ... nthArray);
The above syntax needs no explanation. Let's look at an example:
const favFruits1 = ['apple', 'banana'];
const favFruits2 = ['orange', 'pinapple'];
const addFavFruits = favFruits1.concat(favFruits2);
console.log(addFavFruits); // Output: ['apple', 'banana', 'orange', 'pineapple']
You can add any number of arrays together using this concat()
method.
some()
method:
You use the some()
method when you want to determine whether an array contains at least one element that meets a particular condition. For instance, you can use it to check if there's at least one positive number, if any user in a list is over a certain age, or if an array contains a specific value.
The syntax is:array.some(function(element[, index[, array]]));
The syntax may seem confusing but with an example, you'll understand it better.
But before that, please note that the some()
method usually returns a boolean as output. If the condition specified is met, it returns true
, otherwise, the result will be false
.
Example:
const examScores = [52, 27, 63, 74, 85];
// Check if there's at least one even number in the array
const hasEvenNumber = examScores.some(function(number) {
return number % 2 === 0;
});
console.log(hasEvenNumber); // Output: true (because 52 and 74 are even)
Let's look at a second example:
const myFriends = [
{ name: 'Gideon', age: 25 },
{ name: 'Emmanuel', age: 28 },
{ name: 'Osinachi', age: 42 }
];
// Check if there's at least one friend older than 30
const hasMyFriendOver30 = myFriends.some(function(friend) {
return friend.age > 30;
});
console.log(hasMyFriendOver30); // Output: true (Osinachi is older than 30)
Task 3: This is your last task in this post. There is another method for testing arrays called every(). Find out what it does and how it works. Send me your answer in my DM on Twitter.
Conclusion
In this complete guide, we've thoroughly covered JavaScript's array methods, equipping you with the skills needed to efficiently manipulate and transform arrays in your code. You've learned the ins and outs of basic operations like push
, pop
, shift
, and unshift
, as well as advanced techniques such as map
, some
, reduce
, and forEach
.
By selecting the appropriate method for each task, you can write cleaner and more effective code, thus enhancing both the efficiency and readability of your codes.
Best wishes in your coding endeavours.