Do you want to know what is reduce() method in JavaScript Array and when do we use it? Keep on reading!
In this article, we will explain the reduce() method and you’ll know when you need to use it in your code.
Let’s start to discover common use cases such as summing numbers, calculating averages, and mapping arrays.
Master complex transformations with this versatile method.
What is reduce() in JavaScript?
The reduce() method in JavaScript is used to reduce the array to a single value.
It runs a given function for each item in the array (going from left to right), and the result of the function is kept in a container called an accumulator.
This method operates on each element of the array, in order, to pass in the return value from the calculation on the preceding element.
The ultimate outcome after applying the reducer to all elements in the array is a single value.
Syntax
array.reduce(function(total, currentValue, currentIndex, array), initialValue) ✅
Parameter
The reduce() method in JavaScript takes two parameters:
function (Required) ✅ (first parameter)
This is the callback function that is executed on each element in the array.
The four (4) arguments:
total (or accumulator) (Required)
This is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied.
currentValue (Required)
This is the current element being processed in the array.
currentIndex (Optional)
This is the index of the current element being processed in the array.
array (Optional
This is the array reduce() was called upon.
initialValue (Optional) ✅ (2ndparameter)
This is a value to be used as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used.
Return value
The return value of the reduce() method is the value that results from the reduction.
In other words, it’s the final, single output value that we end up with after running each element of the array through our reducer.
Here’s an example:
const samplearray = [10, 20, 30, 40, 50];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 10 + 20 + 30 + 40 + 50
console.log(samplearray.reduce(reducer)); ✅
// expected output: 150
// 50 + 10 + 20 + 30 + 40 + 50
console.log(samplearray.reduce(reducer, 50)); ✅
// expected output: 200
Output:
150
200
When to use reduce JavaScript?
The reduce() method in JavaScript is a powerful tool that can be used in a variety of scenarios.
Here are some common use cases:
Adding numbers together
The primary way that reduce() is often used is to calculate the total of all the numbers within an array.
For instance, if you possess an array of different amounts and your goal is to find their sum, you can achieve this by employing the reduce() function.
const samplearray = [11.5, 22.5, 33, 44, 55.5];
const reducer = (accumulator, currentValue) => accumulator + currentValue; ✅
console.log(samplearray.reduce(reducer));
Output:
166.5
Calculating an average
Another application of reduce() is determining the average value of the numbers within an array.
This is achieved by dividing the sum of the numbers by the array’s length and then providing this computed value as the end result.
Here’s an example:
const samplearray = [11.5, 22.5, 33, 44, 55.5];
const average = samplearray.reduce((total, amount, index, array) => {
total += amount;✅
if( index === array.length-1) {
return total/array.length;
} else {
return total;
}
});
console.log(average);
Output:
33.3
Mapping with reduce
You can utilize reduce() to change an array into a different array where each item is adjusted somehow.
For instance, you might multiply each number by two before adding them together.
Here’s an example:
const samplearray = [10, 20, 30, 40, 50];
const doubled = samplearray.reduce((result, num) => {
result.push(num * 2); ✅
return result;
}, []);
console.log(doubled);
In this example, we used the reduce() method to iterate over the numbers array.
For each number, we double it and then add it to our result array. The second argument to reduce() is an empty array [], which is used as the initial value for our result array.
Output:
[ 20, 40, 60, 80, 100 ]
Complex transformations with reduce()
The reduce() method gives you a lot of flexibility to write any logic you want. It will repeat the logic for each element in the array and then return a single value.
Here’s an example where we use reduce() to transform an array of strings into an object that counts the occurrence of each string:
const subjects = ['Math', 'English', 'Math', 'English', 'Programming', 'English', 'Math', 'Programming'];
const subjectsCounts = subjects.reduce((obj, subject) => ✅ {
if (!obj[subject]) {
obj[subject] = 1;
} else {
obj[subject]++;
}
return obj;
}, {});
console.log(subjectsCounts);
Here, we are using reduce() to iterate over the pets array. For each subject, we check if it exists as a key in our obj object. If it doesn’t exist, we add it with a value of 1.
If it does exist, we increment its value by one. The second argument to reduce() is an empty object {}, which is used as the initial value for our obj object.
Output:
{ Math: 3, English: 3, Programming: 2 }
How to use reduce in JavaScript: A step-by-step guide
The reduce() method in JavaScript is used to apply a function to each element in an array to reduce the array to a single output value.
Here’s how you can use it:
Step 1: Define your array
This is the array that you want to reduce.
Here’s an example:
const array = [10, 20, 30, 40, 50];
Step 2: Define your reducer function
This function will be applied to each element in the array. It takes two arguments: the accumulator and the current value.
The accumulator is the value that you return each time the reducer is run. It represents the accumulated value up to the current point.
const reducer = (accumulator, currentValue) => accumulator + currentValue;
In this example, the reducer function adds the current value to the accumulator.
Step 3: Call reduce() on your array
You do this by using the dot notation followed by reduce(), and passing in your reducer function as an argument.
console.log(array.reduce(reducer));
In this example, reduce() adds up all the numbers in the array and outputs 15.
You can also provide an initial value as a second argument to reduce(). This will be used as the initial value of the accumulator.
console.log(array.reduce(reducer, 5));
In this example, reduce() starts with an initial accumulator value of 5, then adds up all the numbers in the array, and outputs 20.
Conclusion
The reduce() method in JavaScript is used to transform an array into a single value.
It does this by applying a function to each element in the array, from left to right, and accumulating the results.
The method is versatile and can be used for a variety of tasks such as summing numbers, calculating averages, and mapping arrays.
With reduce(), you can write complex transformations with just a few lines of code.
We are hoping that this article provides you with enough information that help you understand the reduce in JavaScript.
If you want to dive into more JavaScript topics, check out the following articles:
- Replace substring in JavaScript
- Math.sqrt() in JavaScript
- What is Math.power or Math.pow() Method in JavaScript?
Thank you for reading Itsourcecoders 😊.