Arrays are one of the most powerful data structures in JavaScript and are helpful for all sorts of tasks. This blog post will discuss 15 array methods in detail so you can start using them immediately!
If you are working with JavaScript, arrays are something you can’t avoid, so knowing these 15 JavaScript array methods is not only helpful, but it is a must, and they are often the subject of interview questions.
What Are JavaScript Arrays?
A JavaScript array is a data structure that stores multiple values in a single variable. They are similar to other data structures, like lists and dictionaries, but they have some key differences. Arrays are ordered collections of items, so each item has an index. This index can be used to access or modify the items in the array.
Create an Array
You can create an array in JavaScript using any of the following syntaxes:
Create an array by encapsulating array elements in squared brackets:
const array_name = [item1, item2, ...];
Alternatively, you can start with an empty array and fill the array:
const array_name = [];
array_name[0]= item1;
array_name[1]= item2;
array_name[2]= ...;
Or you can use the keyword new
with the array constructor:
const array_name = new Array(item1, item2, ...);
And there are more clever and fun ways of doing that, but that will have to be for another article.
Why Are JavaScript Arrays So Good?
JavaScript arrays are powerful because they provide a lot of methods to manipulate data. These methods make it easy to perform everyday tasks, such as:
- Adding and removing elements from an array
- Searching for an element in an array
- Sorting the elements in an array
- Looping through an array
- Filtering an array
And much more!
So, without further ado, let’s get started with the 15 must-know JavaScript array methods.
Method #1: Some()
The some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
This is how you use it:
arr.some(callback(element[, index[, array]])[, thisArg])
The some()
method executes the callback function once for each element present in the array until it finds one where callback
returns a truthy value (a value that coerces to true
). It returns’ false’ if it doesn’t find such an array element.
Example:
const a = [1, 2, 3, 5, 8].some(item => item > 5)
const b = [1, 2, 3, 4, 5].some(item => item > 5)
console.log(a)
console.log(b)
---------
Output
---------
> true
> false
Method #2: Every()
The every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
This is how you use it:
arr.every(callback(element[, index[, array]])[, thisArg])
The every()
method executes the callback function once for each array element until it finds one where callback()
returns a falsy value (a value that coerces to false). It returns true
if it doesn’t find such an array element.
Example:
const a = [10, 9, 8, 7, 6].every(item => item > 5)
const b = [7, 6, 5].every(item => item > 5)
console.log(a)
console.log(b)
---------
Output
---------
> true
> false
Method #3: Reduce()
The reduce()
method executes a reducer function (that you provide) on each array element, resulting in a single output value.
The reducer function takes four arguments:
- accumulator
- currentValue
- currentIndex
- array
The first time the callback
is called, accumulator
and currentValue
can be either the initialValue
if provided or the first array element if not.
Definition:
arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
How reduce() works
Let’s see with an example how reduce()
works:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue)
If we go step by step and put in a table all the parameters plus the resulting value of the callback
, we would get the following:
# | accumulator | currentValue | currentIndex | array | return value |
---|---|---|---|---|---|
1 | 0 | 1 | 0 | [0, 1, 2, 3, 4] | 1 |
2 | 1 | 2 | 1 | [0, 1, 2, 3, 4] | 3 |
3 | 3 | 3 | 2 | [0, 1, 2, 3, 4] | 6 |
4 | 6 | 4 | 3 | [0, 1, 2, 3, 4] | 10 |
And the final result would be 10
. In our particular case, I did not provide an initial value. Let’s try that next.
const initialValue = 10
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue, initialValue)
With this new scenario, our table would like:
# | accumulator | currentValue | currentIndex | array | return value |
---|---|---|---|---|---|
1 | 10 | 0 | 0 | [0, 1, 2, 3, 4] | 10 |
2 | 10 | 1 | 1 | [0, 1, 2, 3, 4] | 11 |
3 | 11 | 2 | 2 | [0, 1, 2, 3, 4] | 13 |
4 | 13 | 3 | 3 | [0, 1, 2, 3, 4] | 16 |
5 | 16 | 4 | 4 | [0, 1, 2, 3, 4] | 20 |
And the final resulting value is 20
.
The reduce()
function is great. It has several uses, like summing all the values of an array or in an object array, counting for particular items in the array, grouping objects, merging arrays contained in an array of objects, removing duplicates, etc.
If you want to know more about reduce()
check our guide on JavaScript reducer, a simple, yet powerful array method
Method #4: Map()
The map()
method creates a new array with the results of calling the provided function on each array element.
The function takes three arguments:
- currentValue
- index (optional)
- array (optional)
In order, the map()
method calls the provided function once for each element in an array. It does not execute the callback
on elements without values. The return value of the callback function is stored in the new array.
Definition:
arr.map(callback( currentValue[, index[, array]])[, thisArg])
Always be careful when using
map()
. Remember that for each element, JavaScript creates an array. If you don’t need the resulting array and want to iterate the array elements, useforEach()
orfor-of
instead.
Example:
const numbers = [1, 2, 3, 4, 5]
const doubled = numbers.map(value => value * 2)
console.log(doubled)
---------
Output
---------
> (5) [2, 4, 6, 8, 10]
As we mentioned, map()
will create a new array, so the following is a consequence of that:
const numbers = [1, 2, 3, 4, 5]
const numbers2 = numbers.map(value => value)
console.log('numbers', numbers)
console.log('numbers2', numbers2)
console.log(numbers === numbers2)
---------
Output
---------
numbers (5) [1, 2, 3, 4, 5]
numbers2 (5) [1, 2, 3, 4, 5]
false
Even though each array contains the same elements, they are not the same reference. Thus the numbers === numbers2
resolves to false.
Method #5: Flat()
The flat()
method creates a new array with all sub-array elements concatenated recursively up to the specified depth. The default depth is one.
Examples:
const arr1 = [1, 2, [3, 4]]
console.log(arr1.flat())
const arr2 = [1, 2, [3, 4, [5, 6]]]
console.log(arr2.flat())
const arr3 = [1, 2, [3, 4, [5, 6]]]
console.log(arr3.flat(2))
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]
console.log(arr4.flat(Infinity))
---------
Output
---------
> (4) [1, 2, 3, 4]
> (5) [1, 2, 3, 4, Array(2)]
> (6) [1, 2, 3, 4, 5, 6]
> (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note that if we want to flatten all levels recursively, we can pass
Infinity
as the function’s argument.
Method #6: Filter()
The filter()
method creates a new array with all elements that pass the given test implemented by the provided function.
The filter()
method does not mutate the original array but returns a new one.
Definition:
arr.filter(callback(element[, index, [array]])[, thisArg])
Examples:
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i == 0) {
return false
}
}
return num > 1
}
console.log(array.filter(isPrime))
---------
Output
---------
> (6) [2, 3, 5, 7, 11, 13]
From the example above, we use a filter()
method with a callback function to test whether each element of an array is a prime number or not. The resulting new array only contains the elements of an array that are prime numbers.
Method #7: ForEach()
The forEach()
method executes the provided function once for all the elements in the array. It differs from the map()
method because it does not create a new array.
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
Definition:
arr.forEach(callback(currentValue [, index [, array]])[, thisArg])
Example:
const array = [1, 2, 3, 4, 5]
array.forEach((item) => console.log(item))
---------
Output
---------
1
2
3
4
5
There are two critical considerations when using forEach()
:
- There is no way to stop or break a
forEach()
loop other than throwing an exception. -
forEach()
expects a synchronouscallback
, it won’t wait for promises to be resolved.
Let’s see an example of the latter:
let ratings = [5, 4, 5]
let sum = 0
let sumFunction = async function (a, b)
{
return a + b
}
ratings.forEach(async function(rating) {
sum = await sumFunction(sum, rating)
})
console.log(sum)
---------
Output
---------
0
The expected outcome for the above example would have been 14
, but we got 0
instead. The forEach()
array method did not await the promise, and the console.log()
statement was executed before the variable sum
was updated.
If you want to know more about forEach()
check our guide on looping arrays with JavaScript forEach
Method #8: FindIndex()
The findIndex()
method returns the index of the first element in an array that satisfies a given test function. Otherwise, it returns -1
. Unlike other methods, findIndex()
will execute the given function even for indexes with unassigned values.
Definition:
arr.findIndex(callback( element[, index[, array]] )[, thisArg])
Example:
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i == 0) {
return false
}
}
return num > 1
}
console.log([4, 6, 8, 9, 12].findIndex(isPrime))
console.log([4, 6, 7, 9, 12].findIndex(isPrime))
---------
Output
---------
-1
2
As we can see from the example above, findIndex()
returns -1
if an array does not contain any prime numbers and the index of the first element that’s a prime number.
Method #9: Find()
The find()
method returns the value of the first element in an array that satisfies a given test function. Otherwise, it returns undefined
. Note the difference with findIndex()
, where the element’s index is returned instead of the value.
Definition:
arr.find(callback(element[, index[, array]])[, thisArg])
Example:
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
]
const result = inventory.find( ({ name }) => name === 'cherries' )
console.log(result)
---------
Output
---------
> {name: "cherries", quantity: 5}
Method #10: Sort()
The sort()
method returns a new sorted array with the elements sorted in ascending order. When called with no arguments, the array is sorted alphabetically by converting each element to a string and comparing these strings using Unicode code point value.
Sorting is among the most popular js array methods, yet it is sometimes misused, as it has a few particularities.
Examples:
const numbers = [4, 2, 5, 1, 3]
numbers.sort((a, b) => a - b)
console.log(numbers)
---------
Output
---------
> (5) [1, 2, 3, 4, 5]
Always remember that the sorting happens in place, so:
const numbers = [4, 2, 5, 1, 3]
const numbers2 = numbers.sort((a, b) => a - b)
console.log('numbers', numbers)
console.log('numbers2', numbers2)
console.log(numbers === numbers2)
---------
Output
---------
numbers > (5) [1, 2, 3, 4, 5]
numbers2 > (5) [1, 2, 3, 4, 5]
true
The sort function will modify the original array and return a reference to itself. Thus, the initial array and the returned array are the same.
Method #11: Concat()
The concat()
method merges two or more arrays into a single javascript array. This method does not alter the original but returns a new array instance containing all the elements from both arrays.
Definition:
const new_array = old_array.concat([value1[, value2[, ...[, valueN]]]])
Examples:
const letters = ['a', 'b', 'c']
const numbers = [1, 2, 3]
console.log(letters.concat(numbers))
---------
Output
---------
> (6) ["a", "b", "c", 1, 2, 3]
Method #12: Fill()
The fill()
method sets all the elements in an array, from a start index to an end index, with a static value. It returns a new array object without altering the original one.
Definition:
arr.fill(value[, start[, end]])
Examples:
const original = [1, 2, 3]
const result = original.fill(4)
console.log('original', original)
console.log('result', result)
console.log(original === result)
---------
Output
---------
original > (3) [4, 4, 4]
result > (3) [4, 4, 4]
true
Method #13: Includes()
The includes()
method returns true
or false
depending on whether a given value is present among the array elements. It is similar to the indexOf()
method, but instead of returning the index, it returns just a boolean indicating its presence in the array.
Definition:
arr.includes(valueToFind[, fromIndex])
Examples:
console.log([1, 2, 3].includes(2))
console.log([1, 2, 3].includes(4))
---------
Output
---------
true
false
Note that includes is case-sensitive when dealing with strings.
Method #14: Reverse()
The reverse()
method reverses an array in place. By reversing, we mean that the function will transpose the elements of the array. The first element will become the last, and the last the first element.
This operation will mutate the original array and return a reference to the same.
Definition:
a.reverse()
Examples:
console.log([1, 2, 3].reverse())
---------
Output
---------
> (3) [3, 2, 1]
A typical use case for reverse()
is, for example, if you have an array of comments and want to display them in reverse chronological order.
Method #15: FlatMap()
The flatMap()
method applies a function to each array element and then flattens the result into an array. It combines flat()
and map()
in one function.
Definition:
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])
Example:
const array = [[1], [2], [3], [4], [5]]
const a = array.flatMap(arr => arr * 10)
// With .flat() and .map()
const b = array.flat().map(arr => arr * 10)
console.log('flatMap', a)
console.log('flat&map', b)
---------
Output
---------
flatMap (5) [10, 20, 30, 40, 50]
flatMap (5) [10, 20, 30, 40, 50]
Bonus: Add and Remove Array Elements with Push() and Pop() and Shift()
push()
The push()
method adds one or more elements to the end of an array and returns the new length of the new array. It mutates the array in place. The elements are added one by one after the last array element, in the order in which they appear in the arguments list.
Example:
const fruits = ["🍌", "🍊", "🍎"];
fruits.push("🥝", "🍋");
console.log(fruits); // output: ['🍌', '🍊', '🍎', '🥝', '🍋']
pop()
The pop()
method removes the last array element and returns that removed element. It mutates the array in place.
Example:
const fruits = ["🍌", "🍊", "🍎"];
const popped = fruits.pop(); // remove last element
console.log(fruits); // output: ['🍌', '🍊']
console.log(popped); // output: 🍎
shift()
The shift()
method removes the first element from an array and returns that removed element. It mutates the array in place.
Example:
const fruits = ["🍌", "🍊", "🍎"];
const shifted = fruits.shift(); // remove first array element
console.log(fruits); // output: ['🍊', '🍎']
console.log(shifted); // output: 🍌
These methods are particularly useful when dealing with stacks or queues. A stack is a data structure that allows you to store and retrieve data in a last-in, first-out (LIFO) order. A queue is a data structure that allows you to store and retrieve data in a first-in, first-out (FIFO) order.
Summary
In this article, we have gone over the most important JavaScript array methods. Knowing them can save us some time and in some cases even boost the performance of our code.
I hope that today you learned some new arr y methods, or refresh old concepts which you can use for your next project.
Do you know any other interesting JavaScript array methods? Let me know in the comments below.
Happy coding!
Newsletter
Subscribe to my weekly newsletter for developers and builders and get a weekly email with relevant content.
Top comments (0)