In this article, you will learn about the javascript Array built-in method Array.prototype.reduce()
. How does this method work in javascript?
The Array.prototype.reduce()
method executes a user-supplied "reducer" callback function on each element of the array, from left to right and it returns a single value.
array.reduce(callback(previousValue ,currentValue, currentIndex, array) ,initialValue);
This method takes 2 parameters as given below:
initialValue
is specified, otherwise the value of previousValue
is array[0]
.array[0]
if an initialValue
was specified, otherwise the value of array[1]
.currentValue
in the array. On the first call, if initialValue
was specified then it will be 0
, otherwise 1
.callback
function on the first call. If initialValue
is not provided, the first element acts as the initialValue
on the first call, and callback
function won't execute on it.The reduce()
does not change the original array. And it executes a callback function once for each array element in order.
initialValue
is provided but the array is empty, the single value will be returned without calling callback function. Calling the reduce()
method on an empty array without passing the initialValue
will throw TypeError
.Array.prototype.reduce()
method:/*
In this example, you can see how to reduce() method behaves
without passing initialValue
*/
const arr = [40, 90, 160, 250, 360];
function reducer(previousValue, currentValue, index) {
const returns = previousValue + currentValue;
console.log(
`previousValue: ${previousValue}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
);
return returns;
}
arr.reduce(reducer);
/*
The callback would be invoked four times,
with the arguments and return values in each call being as follows:
--------------------------Output---------------------------------
"previousValue: 40, currentValue: 90, index: 1, returns: 130"
"previousValue: 130, currentValue: 160, index: 2, returns: 290"
"previousValue: 290, currentValue: 250, index: 3, returns: 540"
"previousValue: 540, currentValue: 360, index: 4, returns: 900"
*/
In the above example, The array parameter never changes through the process - it's always [40, 90, 160, 250, 360].
The value returned by reduce()
method would be that of the last callback invocation (900).
/*
In this example, you can see how reduce() method behaves
when we passing initialValue
*/
const arr = [40, 90, 160, 250, 360];
function reducer(previousValue, currentValue, index) {
const returns = previousValue + currentValue;
console.log(
`previousValue: ${previousValue}, currentValue: ${currentValue}, index: ${index}, returns: ${returns}`,
);
return returns;
}
arr.reduce(reducer, 100);
/*
The callback would be invoked five times,
with the arguments and return values in each call being as follows:
--------------------------Output---------------------------------
"previousValue: 100, currentValue: 40, index: 0, returns: 140"
"previousValue: 140, currentValue: 90, index: 1, returns: 230"
"previousValue: 230, currentValue: 160, index: 2, returns: 390"
"previousValue: 390, currentValue: 250, index: 3, returns: 640"
"previousValue: 640, currentValue: 360, index: 4, returns: 1000"
*/
The value returned by reduce()
method would be that of the last callback invocation (1000).
const arr = [40, 90, 160, 250, 360, [720, 1440], 2880];
// Flattening an array using reduce() method
console.log(arr.reduce((previousValue, currentValue) => previousValue.concat(currentValue),
[]));
// Output => [40, 90, 160, 250, 360, 720, 1440, 2880]
const arr = [40, 90, 360, 40,160, 250, 360, 720, 1440, 2880, 250];
// Removing a duplicate elements from an array using reduce() method
const newArrayWithNoDuplicates = arr.reduce(
(previousValue, currentValue) => {
if (!previousValue.includes(currentValue)) {
return [...previousValue, currentValue];
}
return previousValue;
},
[],
);
console.log(newArrayWithNoDuplicates)
// Output => [40, 90, 360, 160, 250, 720, 1440, 2880]
let actor = [
{ name: "Tom Holland", age: 21 },
{ name: "Cillian Murphy", age: 45 },
{ name: "Tom Hardy", age: 40 },
{ name: "Ben Affleck", age: 45 },
{ name: "Oscar", age: 21 },
{ name: "Gal Gadot", age: 37 },
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (previousValue, currentValue) {
let key = currentValue[property];
if (!previousValue[key]) {
previousValue[key] = [];
}
previousValue[key].push(currentValue);
return previousValue;
}, {});
}
let groupedPeople = groupBy(actor, "age");
console.log(groupedPeople);
/*
---------------------Output---------------------
{
21: [
{
"age": 21,
"name": "Tom Holland"
},
{
"age": 21,
"name": "Oscar"
}
],
37: [
{
"age": 37,
"name": "Gal Gadot"
}
],
40: [
{
"age": 40,
"name": "Tom Hardy"
}
],
45: [
{
"age": 45,
"name": "Cillian Murphy"
},
{
"age": 45,
"name": "Ben Affleck"
}
]
}
*/
The reduce()
method skips missing elements in sparse arrays, but it does not skip undefined
values in an array.
//reduce() skips the missing element from an array and return a single value
console.log([1, 2, , 4, 5, 6, null].reduce((a, b) => a + b));
// Output => 18
//reduce() does not skip the undefined element from an array
//and return a NaN
console.log([1, 2, undefined, 4, 5, 6].reduce((a, b) => a + b));
// Output => NaN
I hope this article will help you to understand the javascript Array built-in method Array.prototype.reduce().
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments