15 most commonly used array methods in Javascript explained with detailed examples
What is an Array?
An object data type allows you to store collections of data, but, you can only store them in a key-value pair. Due to this, it is very difficult to manage the order of elements In an object.
To solve this issue we make use of a special type of object called, an array. An array is a special type of object that stores data in an ordered form.
How to declare an Array
Javascript arrays can be declared in two ways and they are:
Using square brackets.
This is the common way of creating an array. It is done by wrapping the array's items in a pair of square brackets.
let array = [1, 2, 3, "go"];
Using the Array constructor.
The array constructor does the same thing as the bracket notation. It can be called with or without the new keyword.
But, it has a pitfall, which is that, if it is called with an argument that is a number, then that number will be taken as the length of the array.
let array = new Array(3); let anotherArray = Array(1, 2, 3, "go"); //To check the length of the array console.log( array.length() ); // 3 console.log( anotherArray.length() ) // 4 // To access the first element in array console.log( array[0] ); // undefined console.log( anotherArray[0] ); // 1
In the example above, the array variable has a length of four (i.e it has four elements). But, when we tried to access the first element of the array it returns undefined, which means that the first element has not been assigned a value.
Accessing Elements in an Array
Array elements or members are ordered from the first to the last using a zero-based index. The index denotes the position of each element in the array. This means that the first element will have an index of zero, the second element will have an index of one and so on.
The number of elements in an array determines the length of the array. Arrays in javascript do not have a fixed length
Array elements can be accessed by:
using their index.
You call the name of the array with a square bracket containing the index you want to access.
let newArray = ["Mus3ab", "Njoku", "Clinton"]; // To access first element let firstElement = newArray[0]; console.log(firstElement); // Mus3ab // To access second element let secondElement = newArray[1]; console.log(secondElement); // Njoku // To access third element let thirdElement = newArray[2]; console.log(thirdElement); // Clinton
using the array's length property.
You can get the length of the array using the length property. Then, you will subtract any number from it to get the index of the element you want to access.
let newArray = ["Mus3ab", "Njokwu", "Clinton"]; let length = newArray.length; let firstElement = newArray[length - 3]; console.log(firstElement); // Mus3ab let secondElement = newArray[length - 2]; console.log(secondElement); // Njoku let thirdElement = newArray[length - 1]; console.log(thirdElement); // Clinton
using a loop
Array elements can be accessed by using loops. You can use a for loop or a while loop.
let newArray = ["Mus3ab", "Njokwu", "Clinton"]; for (let i = 0; i < newArray.length; i++) { return newArray[i] }
What are array methods?
Array methods are functions that perform certain actions. Array methods act on arrays.
There are over twenty array methods in Javascript but, fifteen of them are commonly used. In this article, you will learn the fifteen most commonly used array methods in Javascript.
Array methods can be called by adding a dot with the method you are calling to the array's name.
let family = ['father', 'mother', 'children'];
// To apply the push() method on the family array
family.push("child");
In the example above, the push() method was applied to the family array by appending it with a dot to the array name.
The fifteen most commonly used array methods can be grouped based on the action they perform on an array. There are:
Methods that add or remove elements.
Methods used to search among elements.
Methods used to iterate over elements.
Methods used to transform an array.
Methods that add or remove elements
Items can be added to an array and also removed from an array. To add or remove items from an array you can use these methods.
push()
pop()
shift()
unshift()
splice()
slice()
concat()
push()
You can add an item to the end of an array with the push() method. It takes as an argument, the item that is to be added to the array.
let array = ["boy", "girl", "man"];
// To add an item to the end of the array
array.push("woman");
console.log(array); // ["boy", "girl", "man", "woman"]
pop()
If you want to remove the last item of an array you make use of the pop() method. This method takes as an argument, the item to be removed from the array.
let array = ["boy", "girl", "man", "woman"];
// To remove an item from the end of the array
let removedItem = array.pop()
console.log(removedItem); // woman
console.log(array); // ["boy", "girl", "man"]
unshift()
The unshift() method is the opposite of the push() method. It adds an item to the beginning of an array.
let fruits = ["orange", "banana"];
// To add an item to the beginning of an array
fruits.unshift("pawpaw");
console.log(fruits); // ["pawpaw", "orange", "banana"]
shift()
Similar to the unshift() method, this method is the opposite of the pop() method. It removes an item from the beginning of an array.
let fruits = ["pawpaw", "orange", "banana"];
// To remove an item from the beginning of an array
let removedItem = fruits.shift();
console.log(removedItem); // "pawpaw"
console.log(fruits); // ["orange", "banana"]
splice()
The splice() method is multifunctional (i.e it has more than one use). It can insert, delete and replace items of an array.
It takes three arguments
The start index.
The delete count.
The item or items to replace with or be inserted.
To delete an item or items you will set the start index to the index you want to start deleting from and the delete count to the index immediately after the index you want to stop the deletion at.
let fruits = ["pawpaw", "orange", "banana"];
// To delete an element
fruits.splice(0, 1);
console.log(fruits); // ["orange", "banana"]
To insert an item or items you will set the delete count to zero and your third argument will be the item or items you want to insert.
let fruits = ["pawpaw", "orange", "banana"];
// To insert elements
fruits.splice(2, 0, "mango", "carrot");
console.log(fruits); // ["pawpaw", "orange", "mango", "carrot", "banana"]
To replace an item, you will set the delete count to the number of items you want to replace and the third argument will be the item or items you want to replace them with.
let fruits = ["pawpaw", "orange", "banana"];
// To replace elements
fruits.splice(1, 2, "mango", "carrot");
console.log(fruits); // ["pawpaw", "mango", "carrot"]
slice()
The slice() method is used to copy an array. If it is called without an argument, then it copies the whole array into a new array.
It takes two arguments which are, the start index and the index immediately after the index it should stop at.
let fruits = ["pawpaw", "orange", "banana"];
let slicedArray = array.slice(0, 2)
console.log(slicedArray); // [pawpaw", "orange"]
concat()
The concat() method creates a new array whereby it copies the items of the old array alongside the items of the arrays or the items passed into it as arguments.
It can take as arguments a single item, an array or a collection of items and arrays.
let fruits = ["pawpaw", "orange", "banana"];
let concatedFruits = fruits.concat(["apple", "mango"], "carrot", "cashew");
console.log(concatedFruits); // ["pawpaw", "orange", "banana", "apple", "mango", "carrot", "cashew"]
Methods used to search among elements
The following methods are used to search among elements in an array
indexOf()
includes()
find()
filter()
findIndex()
indexOf()
The indexOf() method returns the index where an item can be found. You will pass the item whose index you are searching for, as an argument and also you can pass an optional argument that indicates the index you should start searching from.
It returns minus one if the index is not found.
let fruits = ["pawpaw", "orange", "banana"];
let orangeIndex = fruits.indexOf("orange");
let pawpawIndex = fruits.indexOf("pawpaw", 1);
console.log(orangeIndex); // 1
console.log(pawpawIndex); // -1
includes()
It is similar to the indexOf() method, it takes the same arguments. But, the only difference is that it returns true or false if the item is present or not.
let fruits = ["pawpaw", "orange", "banana"];
let hasBanana = fruits.includes("banana");
let hasOrange = fruits.includes("orange", 2);
console.log(hasBanana); // true
console.log(hasOrange); // false
find()
The find() method returns the first item of an array that passes a condition. You will pass an arrow function to it as an argument.
let fruits = ["pawpaw", "orange", "banana"];
let found = fruits.find(item => item === "orange");
let notFound = fruits.find(item => item === "cashew");
console.log(found); // orange
console.log(notFound); // undefined
filter()
It is similar to the find() method, it returns all items of an array that matches a specific condition.
let fruits = ["pawpaw", "orange", "banana", "grape"];
let filteredFruits = fruits.filter(fruit => fruit.length > 5);
console.log(filteredFruits); // ["pawpaw", "orange", "banana"]
findIndex()
It is also similar to the find() method, but, instead of returning the item, it returns the item's index.
It returns minus one if the index is not found.
let fruits = ["pawpaw", "orange", "banana"];
let found = fruits.findIndex(item => item === "orange");
let notFound = fruits.findIndex(item => item === "cashew");
console.log(found); // 1
console.log(notFound); // -1
Methods used to iterate over elements
There is only one method that can be used to iterate over items of an array and it is the forEach() method.
forEach()
The forEach() method loops through the array and calls a function for every element of the array.
let fruits = ["pawpaw", "orange", "banana"];
fruits.forEach(fruit => console.log(fruit));
// "pawpaw"
// "orange"
// "banana"
Methods used to transform an Array
The following methods are used to transform an array.
map()
sort()
reverse()
reduce()
map()
The map() method iterates through the elements of an array and calls a function on each element of the array and returns a new array that contains the result of each function call.
let fruits = ["pawpaw", "orange", "banana"];
let mappedFruits = fruits.map(item => item + "s");
console.log(mappedFruits); // ["pawpaws", "oranges", "bananas"]
sort()
The sort() method sorts an array in place and returns the same array in a sorted form.
The default order of the sort() method is ascending order. Strings are sorted in alphabetical order.
let numbers = [4, 3, 5];
let fruits = ["pawpaw", "orange", "banana"];
let sortedNumbers = numbers.sort();
let sortedFruits = fruits.sort()
console.log(sortedNumbers); // [3, 4, 5]
console.log(sortedFruits); // ["banana", "orange", "pawpaw"]
reverse()
The reverse() method reverses the order of items in an array. It reverses the items in the opposite direction to how they were initially arranged.
let fruits = ["pawpaw", "orange", "banana"];
let reversedFruits = fruits.reverse();
console.log(reversedFruits); // ["banana", "orange", "pawpaw"]
reduce()
The reduce method iterates over all the elements of an array and takes an action on each iteration, but the result of that action is carried on to the next iteration to be used in the next action till the final iteration. Then, the final result will be returned.
It takes two arguments, which are:
a function
an optional argument that denotes the value the function will start from
let evenNumbers = [2, 4, 6, 8, 10];
evenNumbers.reduce((sum, current) => sum += current, 0);
In addition to all these, There is a method to confirm if a variable is an array or not. The method is the Array.isArray() method.
It returns true if the passed argument is an array otherwise, it returns false
let myString = "Array"
let yourArray = [1, "string"]
let ourObject = {
age: 12,
class: "foundation"
}
let firstConfirmation = Array.isArray(myString);
let secondConfirmation = Array.isArray(yourArray);
let thirdConfirmation = Array.isArray(ourObject);
console.log(firstConfirmation); // false
console.log(secondConfirmation); // true
console.log(thirdConfirmation); // false
To wrap it up
These are the most commonly used array methods in Javascript, I hope that by now you should have understood them and be able to use them in your code.
Other array methods were not covered in this article, you can check them all out on the Mozilla developer network's website.
Thanks for taking the time to read this article, you should like this article if you feel it was an interesting read and also share it with other people you know.
Also, don't forget to drop your comments if you find any aspect of this article you would like to correct or add to.