In this article, we take a look at some useful methods when working with arrays in Javascript. Generally, some javascript array methods accepts a callback function as an argument, executes it and returns some value, while others simply accepts a list of parameters and execute the logic for that specific method using the provided parameters. Note that it's very easy to practice these as you read along on your console (Ctrl+ Shift +I)
. Here is a list of the methods that this article covers :
arr.push(arg)
arr.pop()
arr.shift()
arr.unshift(callback)
arr.reduce(callback)
arr.filter(callback)
arr.map(callback)
arr.find(callback)
arr.concat(arg1,arg2,...,argN)
arr.indexOf(arg)
arr.lastIndexOf(arg)
arr.splice(index[,count,arg1,arg2,...,argN])
arr.forEach(callback)
1. arr.push(arg)
This method simply appends a new element arg
to the array thus incrementing the length of the array by 1. For example, if we have an array of numbers:
let coolNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
coolNums.push(11)
would push 11 into our array of numbers:
coolNums.push(11)
console.log(coolNums)
//output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
2. arr.pop()
This method simply pulls out and return the last element in an array thus decrementing the length of the array by 1. If called multiple times, it removes an element from the array each time until the array becomes empty. Going back to our coolNums
array, let's pop out the last element 11
that we just added:
coolNums.pop()
console.log(coolNums)
//output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
3. arr.shift()
The array method works just like the arr.pop()
method but in the reverse direction. Rather than removing the last element from the array, arr.shift
pulls out and returns the first element in the array thereby also decreasing the length of the array by 1. For example, calling arr.shift()
3 times on our coolNums
array would look like this :
coolNums.shift() // returns 1
coolNums.shift() // returns 2
let thirdEl = coolNums.shift() // returns 3 and we assigned it to a variable
console.log(coolNums)
//output: [4, 5, 6, 7, 8, 9, 10]
4. arr.unshift(arg)
This method is similar to the arr.push()
method. It adds a new element to an array but at the beginning.
coolNums.unshift(0)
console.log(coolNums)
//output: [0, 4, 5, 6, 7, 8, 9, 10]
5. arr.reduce(callback)
This method takes a callback function and an optional second parameter. The callback function is passed the following parameters :
accumulator
: A variable that holds the aggregate of results of some computations that were carried out while indexing each element in the array.element
: The current element being indexed.index
: The positional index of the current element.array
: The original array object.
Note that the optional second parameter passed to the method after the callback sets the initial value for the accumulator. Say, for example, we want to sum all the numbers in our coolNums
array together and return the sum using the reduce
method, our code would look like this:
let sum = coolNums.reduce((accumulator, element, index, arr) => {
accumulator += element
}, 0)
console.log(sum)
//output: 49
Since index
and arr
are optional arguments that we don't really need, our code would still function the same if we refactor it like this :
let sum = coolNums.reduce((accumulator, element) => {
accumulator+=element
return accumulator
}, 0)
console.log(sum)
//output: 49
You can observe that each time the callback is called we return the accumulator
otherwise the value for our sum
variable would be undefined
.
6. arr.filter(callback)
This method takes a callback function that is passed the element
being indexed, the index
of the current element and the original array
as parameters. It returns a new array which contains element the element that satisfies the condition specified in the callback function. Say, for instace, we want to return all even numbers in our coolNums
array. Our callback function would look like this:
function filterEvenNumbers(number,index,arr){
return number != 0 && number % 2 === 0
}
An even number can be defined as a non-zero number which when divided by 2, returns a remainder of 0
. Hence if this is true for a number, it is returned, otherwise it is skipped. Also, just like in the previous method, the index
and arr
methods are optional.
Now using our filtering function to filter out even numbers in our coolNums
array:
let evenNums = coolNums.filter(filterEvenNumbers)
console.log(evenNums)
//output: [2, 4, 6, 8, 10]
7. arr.map(callback)
This method also accepts the element
, the index
and array
parameter just like the arr.filter
method. This method simply iterates through all elements in the array and executes the callback function each time. It is usually used to return a modified version of the elements in the original array into a new array. For example, if we want to return the square of each element in our original array coolNums
into a new array coolNumsSquared
, the code would look like this :
let coolNumsSquared = coolNums.map(number => number * number)
console.log(coolNumsSquared)
//output: [0, 16, 25, 36, 49, 64, 81, 100]
8. arr.find(callback)
This method takes a callback function and returns just the first element that satisfies the condition specified in the callback function. For this example, we are going to use a different array. Let's say we have an array of brands:
let brands = ["Versace", "Gucci", "Giorgio Armani"]
and we want to find the first brand that starts with "gu"
using this method, our code would be :
let aBrand = brands.find(brand => brand.toLowerCase().startsWith("gu"))
console.log(aBrand)
//output: "Gucci"
9. arr.concat(arg1, arg2,...,argN)
This method is generally used to concatenate arrays together. It returns a single array that consists of all the elements that are contained in each of the passed arrays. Even if primitive values are passed alongside arrays as arguments to this method, it still concatenates everything as a single whole. For example:
let morebrands = brands.concat(["Dolce & Gabbana", "Tommy Hilfiger", "Al Mumais"])
let moreNums = coolNums.concat([11,12,13], 14, 15)
console.log(morebrands)
//output: ["Versace", "Gucci", "Giorgio Armani", "Dolce & Gabbana", "Tommy Hilfiger", "Al Mumais"]
console.log(moreNums)
//output: [0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
10. arr.indexOf(arg)
This method returns the index of the passed argument. If this element does not exists, the method returns -1. It is useful for deleting elements from an array when used in combination with the arr.splice()
method which is discussed further below. For example, let's say we want to find the index of "Giorgio Armani"
in our brands
array using this method, our code would be:
let indx = brands.indexOf("Giorgoi Armani")
console.log(indx)
//output: 2
However let's try to find the index of "Shoprite"
:
console.log(brands.indexOf("Shoprite"))
//output: -1
11. arr.lastIndexOf(arg)
This method returns the last index of the passed argument. If this element does not exists at all, it also returns -1 just like the arr.indexOf
method. For example :
let counts = [2, 12, 2, 3, 4, 3, 2, 3]
console.log(counts.lastIndexOf(3))
//output: 7
12. arr.splice(index[,count,arg1,arg2,...,argN])
This is a powerful method that is capable of manipuating an array in different ways. It can remove/add and return element(s) from any position in an array. The arguments passed to the callback can be divided into 3 parts:
index
: This is the index to start splicing from.count
: This is the second argument that is passed to the array and it represents the number of elements to be removed from the array.arg1,arg2,...,argN
: This third part of the argument is a list of parameters that is used to fill up the array aftercount
number of elements starting from the givenindex
has been removed from the array. This method actually modifies the array rather than returning a new array like some of the other array methods do. For the following examples, we are using themoreNums
array that we created earlier.
console.log(moreNums)
// output: [0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
- Removal without Insertion
let indx = moreNums.indexOf(4)
moreNums.splice(indx,3) // removes 4, 5, 6
console.log(moreNums)
//output: [0, 7, 8, 9, 10, 11, 12, 13, 14, 15]
- Removal with Insertion
moreNums.splice(1, 2, 1, 2, 3, 4, 5, 6, 7)
console.log(moreNums)
//output: [0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15]
In the example above, the method starts from index 1
which contains the number 7
and deletes two (i.e the second index) items 7
and 8
and finally replaces them with numbers 1
to 8
.
- Insertion without removal
Looking at the last output, the number 8
is missing from our moreNums
array. The code for inserting it at the correct position using arr.splice()
is:
let indx = moreNums.indexOf(9)
moreNums.splice(indx, 0, 8)
console.log(moreNums)
//output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In the code above, we start from the index of the number 9
(since it is in the position of 8
), removed no element(s) and added 8
to the array.
13. arr.forEach(callback)
This method is an alternative to the tranditional for...loop
control structure for looping over the elements of arrays. The arguments passed to the callback are the current element
being indexed, the index
of the current element and the array
itself although in some cases the latter two are ignored. As a trivial example, we are going to log each element in our moreNums
array and the corresponding index using this method :
moreNums.forEach((num, index) => {
console.log(`index: ${index} num: ${num}`)
})
/**
* output:
* index: 0 num: 0
* index:1 num: 1
* index:2 num: 2
* index:3 num: 3
* ...
* /
Conclusion
Pheww, that was a handful. We have come to the end of this article. Please note that this is not an exhaustive list of array methods that are available in Javascript. These are just some commonly used ones. Thanks for reading.
Here is the main resource that was used in preparing this article in case you want to check it out: