In this post, we will grasp the concept of the javascript reduce() function. What is a reduce() function, and how can we use it to help in simplifying the Javascript code and complete the tasks efficiently and most quickly.
What is the reduce() function?
Javascript’s reduce() function for the array is used to reduce the array into a single output value.
The reduce() function takes the element of an array one-by-one, performs an operation, and returns a single output value. Let’s explore and dig more into it to understand the syntax and its functionality, along with a couple of examples.
Syntax:
The interesting part of the array’s reduce() function is that it can take a callback function with four arguments. The syntax of the callback function and the sequence of arguments will go like this:
...
}
In the call back function of reducing () method:
- The first parameter is an accumulator that stores the result after each iteration.
- The second parameter/argument contains the value of the current array element during the iteration.
- The third parameter is the optional parameter which is the current index of the array element during the iteration.
- Lastly, we can also pass the array itself to the callback function for having some custom functionalities inside the callback function.
We can also pass the initial value to the function. The initial value will be the starting value of the accumulator.
Let’s try a couple of examples to see its implementations
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).
How to use reduce() function in JavaScript
The best example to understand the reduce() function is the addition of numbers stored in the array elements.
Example 1:
Suppose we have an array of numbers and we want to add all of these numbers:
The first way to add these numbers is to use a for loop:
for (leti = 0; i<numbers.length; i++) {
sum = sum + numbers[i];
}
console.log(sum);
Although we have got the Sum as output, why not use a smart and easy way to perform the same calculation using the reduce() method of the array, where we do not have to mutate the variables like “sum.”
Using of reduce() function:
The reduce() function to calculate the sum will go like this:
function addNumbers(total, num) {
return total + num
}
console.log(sum);
In the above code, you can see that we have first passed the addNumbers function to the reduce() function, and in the addNumbers function definition, we just added each number to the accumulator variable total and returned its value.
Once the reduce() function adds all the numbers in the numbers array, it will store the final result in the sum variable.
Lastly, we have just consoled the sum variable to verify whether our reduce() function worked fine or not.
By looking in the screenshot provided above, you can verify that the reduce() function has added all the numbers and shown the result in the console, which is 202 and perfectly calculated.
Another shorter and easier way to write reduce() function is to make the callback function an arrow function:
The syntax of writing the callback function within the reduce() function’s parentheses will be like this:
return total + num
}, 0);
console.log(sum);
Alright, this was the simple example in which we have an array of numbers only; what about the array of objects. Let’s try that one as well.
Example 2:
Suppose we have a list of students in an array, and we want to calculate the total fees of all the students:
{
id: 1,
name: "John,"
age: 12,
fee: 8500
},
{
id: 2,
name: "Bob",
age: 14,
fee: 9000
},
{
id: 3,
name: "Steve",
age: 10,
fee: 8000
},
]
The reduce() function to calculate the total fees will go like this:
return total + student.fee
}, 0);
console.log(totalFees);
Now, the only difference in this code is that a single object is passed as a value to the callback function, and inside the definition of the callback function, we have accessed the fee and added it into the accumulator variable.
By looking at the screenshot attached above, you can see that students’ fees are added and displayed as an output. So this is how we can access the objects of an array in the reduce() function.
Conclusion:
In this post, we have learned what a reduce() function is and how we can use it to help in simplifying the Javascript code and completing the tasks efficiently and quickly.
We have learned that the reduce() function reduces the array into a single output value. The reduce() function takes a callback function applied to every element of the array and returns a single output value.
This post is all about JavaScript’s reduce() function and its usage. It contains some basic examples that help in understanding the reduce() function.