Introduction
To have a clear understanding of what higher order array iteration methods are, I am going to define each of these terms separately:
Array
An array is a list-like structure that is used to store a set of values into a single variable.
Iteration
Iteration is simply the process of performing an operation multiple times in order to achieve a particular result. This is basically done using loops.
Method
A method is a function that performs an action on an object.
Higher order function
A higher order function is a function that accepts functions as arguments and/or returns a function as a value.
The functions passed into higher order functions as arguments are called callback functions.
So what are higher order array iteration methods?
Simply put, higher order array iteration methods are functions which accept a callback function that is invoked on each element of an array.
Things to note ๐
For the methods to be considered in this article, we will be using arrow functions to define the callback functions.
In the syntax subsection for each method, optional parameters would be enclosed in set of square brackets.
array.methodName(requiredMethod [, optionalMethod1, optionalMethod2 ])
- The optional parameters would also be italicized in the parameters subsection like so:
requiredMethod
optionalMethod1
optionalMethod2
๐งฌ Methods ๐งฌ
In this article, we are going to go through the following methods:
forEach
Syntax
array.forEach(
function callBackFunction(element [, index, array ]), [ thisArgument ]
)
Or using arrow functions:
array.forEach((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
forEach
is an array iterator that performs an operation on each element of an array.
This method always returns undefined
regardless of whatever is returned from the function body.
It may mutate the original array depending on the content of the function body.
For an array of primeNumbers
:
const primeNumbers = [2, 3, 5, 7, 11];
To print out each element of the array to the console, we would do the following:
primeNumbers.forEach((primeNumber) => {
console.log(primeNumber);
});
In the snippet above, primeNumbers
is not modified, or mutated in any way.
To replace every primeNumber
with its square, we can also use the forEach
method:
primeNumbers.forEach((primeNumber, index, array) => {
array[index] = primeNumber ** 2;
});
In this scenario, forEach
mutates the original array.
map
Syntax
array.map((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
This method iterates over the elements of an array and calls the callback function on each element.
The value returned from the callback function would be stored as an element of the new array returned from map
.
Using the previous example of primeNumbers
, we could achieve the same result of squaring each element without mutating the original array.
const squaresOfPrimeNumbers = primeNumbers.map((primeNumber) => primeNumber ** 2);
filter
Syntax
array.filter((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
The filter
method is used to filter, or separate elements of an array using a test condition.
This test condition must be an expression which evaluates to a boolean value. This expression must then be returned from the callbackFunction
.
filter
returns a new array containing the elements that pass the test condition (evaluated to true
). Elements which fail the test are simply ignored (evaluated to false
).
If we have an array of animals
:
const animals = ['jaguar', 'fox', 'panther', 'antelope'];
Here is how we can filter animals
to include only elements that have the letter, 'a'
.
const filteredAnimals = animals.filter((animal) => animal.includes('a'));
console.log(filteredAnimals);
// ['jaguar', 'panther', 'antelope']
The includes
method returns a boolean value which indicates if an element contains 'a'
or not. The value returned is then used as the test condition for the filter
method.
find
Syntax
array.find((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
The find
method iterates over an array and returns the first element which passes the test condition provided in callBackFunction
.
As with filter
, the test condition must be an expression that would evaluate to a boolean value. This expression must also be returned from callbackFunction
.
If no element passes the test condition, undefined
is returned.
For example, if we have an array of cars
and we want to find the first car which starts with the letter 't'
.
const cars = ['Chevrolet', 'Tesla', 'Land Rover', 'Ferrari', 'Toyota'];
We can use the find
method to perform this operation.
const carStartingWithT = cars.find((car) => car.toLowerCase().startsWith('t'));
console.log(carStartingWithT);
// 'Tesla'
find
is similar in functionality to the filter
method. The only difference is that, once one element passes the test, it is returned and the remaining elements are ignored.
Logically thinking, the first element returned from filter
would be equal to the value returned from the find
method, provided it is the same array.
const carStartingWithT = cars.filter((car) => car.toLowerCase().startsWith('t'))[0];
console.log(carStartingWithT);
// 'Tesla'
findIndex
Syntax
array.findIndex((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
The findIndex
method iterates over an array and returns the index of the first element that passes a test condition.
If no element in the array passes the condition set in callbackFunction
, -1
is returned.
As with find
, the test condition must be an expression that would evaluate to a boolean value, true
or false
. The condition must be returned from the callbackFunction
.
const carIndexStartingWithT = cars.findIndex((car) =>
car.toLowerCase().startsWith('t')
);
some
Syntax
array.some((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element.It must return an expression which would evaluate to a boolean value. This function accepts three parameters:
element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
The some
method executes a callback function on each element of an array and returns a boolean
value, based on the outcome of the operation.
true
- if any of the array elements pass the condition set in the callback function.Once an element passes the test,
true
is immediately returned and the remaining elements are ignored.false
- if no element passes the condition set in the callback function.
Imagine a scenario where we want to check if a string contains a vowel. We could first spread out the string into an array of its characters using the spread syntax.
const alphabets = [...'abcdefghijklmnopqrstuvwxyz'];
const vowels = ['a', 'e', 'i', 'o', 'u'];
For each element in the array, we check if the character is included in the vowels
array. Since 'a'
is in the vowels
array, it passes the condition set in callbackFunction
, and true
is immediately returned from the some
method.
const areVowelsPresent = alphabets.some((alphabet) => vowels.includes(alphabet));
console.log(areVowelsPresent);
// true
every
Syntax
array.every((element[ , index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element.It must return an expression which would evaluate to a boolean value. This function accepts three parameters:
element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
every
is used to check if all the elements of an array pass a condition. This method returns a boolean value.
true
- if all the elements of an array pass the condition set in the callback function.false
- if any of the elements fail the condition set in the callback function.Once an element fails the test,
false
is immediately returned and the remaining elements are ignored.
const areAllVowels = alphabets.every((alphabet) => vowels.includes(alphabet));
console.log(areAllVowels);
// false
On the second iteration, the element 'b'
fails the test condition since it is not included in the vowels
array. false
is immediately returned from the every
method and the remaining elements are not evaluated.
sort
Syntax
array.sort(
[ function compareFunction(firstElement, secondElement) ]
)
array.sort([ (firstElement, secondElement) ])
Parameters
compareFunction
- a callback function which defines the sort order and is invoked on each array element.firstElement
- the first element to be compared.secondElement
- the second element to be compared.
Definition
The sort
method is used to sort the elements of an array using a defined sort order. This method does not create a new array but replaces the original one.
By default, elements are sorted in ascending order, but a compareFunction
can be used to establish the sort order.
The elements to be sorted are first converted to strings and then, sorted in their string form.
For an array of numbers
:
const numbers = [23, 18, 97, 71, 40];
Sorting an array in ascending order (default) would look like this:
const sortedNumbersAsc = numbers.sort();
This is equivalent to:
const sortedNumbersAsc = numbers.sort((a, b) => a - b);
To sort the array in descending order:
const sortedNumbersDesc = numbers.sort((a, b) => b - a);
All undefined
values are sorted to the end of the array.
reduce
Syntax
array.reduce(
function reducer(accumulator, currentValue [, index, array ]),
[ initialValue ]
)
Or using arrow functions:
array.reduce((accumulator, currentValue [, index, array ]),
[ initialValue ]
)
Parameters
reducer
- a callback function which is invoked on every element of the array.accumulator
- this parameter stacks up the values returned fromreducer
on each iteration.currentValue
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
initialValue
- this parameter is used as the initial value ofaccumulator
.If it is not provided, the first element of the array would be used instead.
When this happens, the
reducer
function will not be called on the first element (essentially skipping it), and the second element would be the initialcurrentValue
.
Definition
The reduce
method reduces the elements of an array into a single value by calling a reducer
function on each element.
For example, if we were to find the sum of the first five natural numbers. We could store the numbers in an array and then use the reduce
method to sum up the numbers.
const naturalNumbers = [1, 2, 3, 4, 5];
const naturalNumbersSum = naturalNumbers.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
reduceRight
Syntax
array.reduceRight(
function reducer(accumulator, currentValue [, index, array ]),
[ initialValue ]
)
Or using arrow functions:
array.reduceRight((accumulator, currentValue [, index, array ]),
[ initialValue ]
)
Parameters
reducer
- a callback function which is invoked on every element of the array.accumulator
- this parameter stacks up the values returned fromreducer
on each iteration.currentValue
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
initialValue
- this parameter is used as the initial value ofaccumulator
.If it is not provided, the last element of the array would be used instead.
When this happens, the
reducer
function will not be called on the last element (essentially skipping it), and the penultimate element would be the initialcurrentValue
.
Definition
The reduceRight
method reduces the elements of an array into a single value by calling a reducer
function on each element, traversing the array in a right-to-left manner.
It is very similar to the reduce
method, except that it starts from the end of the array and moves towards the beginning.
We could concatenate all the first characters of string elements in an array using reduceRight
.
const tools = ['Node', 'React', 'Express', 'MongoDB'];
const stack = tools.reduceRight((accumulator, currentValue) => accumulator + currentValue, '');
In this example, we provided an empty string as the initialValue
which would eventually be concatenated with the first characters of the string elements. If we didn't provide this initialValue
, the last element 'MongoDB'
would be used instead.
flatMap
Syntax
array.flatMap((element [, index, array ]), [ thisArgument ])
Parameters
callbackFunction
- the function to be invoked on each element. This function accepts three parameters:element
- the current element in the array.index
- the index of the current element in the array.array
- the array being iterated over.
thisArgument
- value ofthis
insidecallbackFunction
. It has a default value ofundefined
.
Definition
The flatMap
method takes in an array which it first maps through, and then flattens the resulting array with a depth
of 1.
flatten in this context refers to calling the flat
method on an array.
For an array of numbers in which every element is another array containing two elements, base
and exponent
respectively.
const arrayOfNumbers = [[3, 5], [8, 2], [4, 4]];
If we want to raise the base
to the power of the exponent
for each element, and then return the results in a new array, we can use the flatMap
method.
const multiples = arrayOfNumbers.flatMap(([base, exponent = 1]) => base ** exponent));
Using array destructuring, we access the values of base
and exponent
. In the function body, we raise the base
to the power of the exponent
(which has a default value of 1
), and then return the resulting value.
flatMap
is somewhat equivalent to calling the map
method on an array and then flattening the resulting array with a depth
of 1
.
const multiples = arrayOfNumbers.map(([base, exponent = 1]) => {
return base ** exponent;
}).flat();
However, using flatMap
is much more efficient and would have an optimized performance.
I hope you use this new knowledge to build amazing apps.๐ฅ๐ฅ๐
Thanks for reading.๐ฏ๐ฏ
Don't forget to leave a like or comment. ๐