So last week a buddy of mine asked me to help explain .reduce function and I thought it will be better to just write an article explaining it. In this article, I am going to be explaining the reduce function and we will be exploring some examples and use cases in detail.
The reduce() method performs a function on each element of an array and returns a new value. This new value is the result of the function performed on each element in the array. This new value could be an object, a new array, or just a variable. Let's do several examples.
Example 1
We have an array of numbers called array1 and we want to add all the elements in the array and return the final value.
const array1 = [1, 2, 3, 4];
//result=1+2+3+4;
reduce takes in 4 values 2 are compulsory 2 are optional
Accumulator (compulsory)----this is the value of an element after a reduce function has been performed on this element...so if the current value in the index 0 is (1) and your reduce function performs multiplication of 2 on all elements in the array the accumulated value for the index 0 after the reduce function has been performed on it will be (2).
Current Value (compulsory)----This is the current value that is passing through the reduce function.
Current Index (optional)----This is the current index of the value passing through a reduce function.
Source Array (optional)---The array object the current element belongs to
InitialValue (Optional)--A value to be passed to the function as the initial value.If no initial value is specified reduce starts from the first element in the array.
Lets code it up.
const array1 = [1, 2, 3, 4];
const sum = array1.reduce((accumulator, currentValue) => {
accumulator = accumulator + currentValue;
return accumulator;
});
console.log(sum);
sum // 10;
What Happened Here?
reduce started from index 0 of the array which has a value of (1) at this point the accumulator and current value is (1)
It then added the value of index 0 to index 1 whose value is (2). So currently the accumulator is:1+2=3 and the current value is (2).
It then added the value of index 1 to index 2 whose value is (3) the accumulator is now:1+2+3=6 and the current value is (3)
And then finally it added the value of index 2 to index 3 whose value is (4). The accumulator is now:1+2+3+4=10 and the current value is (4)
since that is the last index. It then returns the accumulator value which is =(10).
You can also specify the initial value of the array before the reduce function was called, You can set this value to anything. I can say that the initial value of array1 was (5) so when it is performing its reduce function it adds value 5 first since that is the initial value.
const array1 = [1, 2, 3, 4];
const sum = array1.reduce((accumulator, currentValue) => {
accumulator = accumulator + currentValue;
return accumulator;
}, 5);///setting initial value
console.log(sum)////[5+1+2+3+4]
sum = 15;
Lets go further...supposing we wanted to multiply all the elements of array1 by 2 and then return a new array of the multiplied elements.
const array1 = [1, 2, 3, 4];
///what we want the reduce function to do= [1*2, 2*2,3*2,4*2]
///expected output =[2, 4, 6, 8]
Lets code it up
First we set the initial value to be an empty array(this means that at default the array was empty and it should expect to return an array back) we then push the values that have passed through our function into the empty array and it will now return that array that we initialized.
const array1 = [1, 2, 3, 4];
const sumArray = array1.reduce((accumulator, currentValue) => {
accumulator.push(currentValue * 2);
return accumulator;
}, [];///setting initial value;
sumArray////[2, 4, 6, 8]
Example 3
Finding the average of numbers with the reduce function.In this example we will make use of all the parameters in the reduce function.
const numberss = [1, 2, 3];
const average = numberss.reduce((accumulator,currentvalue, index, array) => {
accumulator += currentvalue;
if( index === array.length-1) {
return accumulator/array.length;
}else {
return accumulator;
}
});
average=2
What Happened Here?
Starting from the value index 0 which is value 1 add it to the next index value. if the index is not equal to the total length of the array which is (3) keep adding it. Once it gets to index 2 which is the last index divide it by the total length of the array and return this value.
Example 4
Grouping elements with reduce function
Lets say you have an array of objects which are tweets
tweets = [
{
tweet: "Messi is the Best",
tweetDate: "June2019",
},
{
tweet: "Ronaldo is the Best",
tweetDate: "August2019",
},
{
tweet: "Pogba is the Best",
tweetDate: "June2019",
},
{
tweet: "Lewadonski is the Best",
tweetDate: "August2019",
},
{
tweet: "Agi is the Best",
tweetDate: "September2019",
},
];
If you want to group these objects by date i.e Group all the tweets that happened in June2019 to one object and August2019 to another object. All objects must have a key and a value so here our key is the tweetDate and the value is the other elements of our object.
What we want to Happen
result = {
June2019: [
{
tweet: "Messi is the Best",
tweetDate: "June2019",
},
{
tweet: "Pogba is the Best",
tweetDate: "June2019",
},
],
August2019: [
{
tweet: "Ronaldo is the Best",
tweetDate: "August2019",
},
{
tweet: "Lewadonski is the Best",
tweetDate: "August2019",
},
],
September2019: [
{
tweet: "Agi is the Best",
tweetDate: "September2019",
}
]
};
Lets code it
const groupTweetsbyDate = () => {
return this.tweets.reduce((accumulator, currentValue) => {
const key = currentValue.tweetDate;
accumulator[key] = accumulator[key]
? [...accumulator[key], currentValue]
: [currentValue];
return accumulator;
}, {})
;
};
console.log(groupTweetsbyDate());
Things to note in the function
...(spread operator)--used to open up an element to a new form so new values can be appended to it.
Example Spread Operator:
if we have array1 =[1,2,3] and array2 =[4,5,6]
const array1 =[1,2,3];
const array2 =[4,5,6];
const result =[...array1,...array2]
console.log(result);
//result= [1,2,3,4,5,6]
Tenary operators(? and :)--- If the lefthand side of (?) = true execute the statement on its right-hand side else execute the statement after the (:);
What Happened Here?
We created a function called groupTweetsbyDate
We performed a reduce function on our array of tweets
If the accumulator tweetDate is equal to a tweetDate that has been loaded into the accumulator. ie if index 0 tweetDate =(June2019) and index 3 tweetDate= (June2019).Since index 0 has been loaded into the accumulator and their tweet Dates are equal. Use the spread operator to open up the current June2019 array and append the index 3 values for June2019 value to it. ELSE---add the currentValues tweetdate values to its own separate array. The same principle applies for August
4.initial value is set to an empty object. So it will return an object of the accumulator values. If you console.log the values you will get.
Remember .reduce() applies a function on every element in an array always remember to add a return statement unless you might run into errors.
Thanks for reading I hope you enjoyed reading this.If you have any questions or you have other cool use cases for the reduce function let me know in the comment section.
Top comments (2)
Great post sir. Didn't really understand much about .reduce() method until now. Keep making articles like this one please. Thank You
You're welcome...Glad I could help