The reduce() method performs a reducer function (provided by you) on each element in the array to get a single output value.
The reduce() method reduces all the elements in an array to a single output value, which can be a number, object, or string. The reduce() method takes two arguments, the first a callback function and the second an initial value.
The callback function
The callback function is executed on each element of the array. The return value of the callback function is the cumulative result and is provided as an argument to the next call to the callback function. The callback function takes four arguments.
- Accumulator — The return value of the Accumulator callback function.
- Current Value – Processes the Current element of the array.
- Current Index – Handles the Index of the Current element of the array.
- Source Array
Current Index and Source Array are optional.
The initial value
If an initialValue is specified, the accumulator is set to initialValue as the initial element. Otherwise, the accumulator is set to the first element of the array as the initial element.
arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])
Copy the code
In the code snippet below, the first accumulator is assigned an initial value of 0. CurrentValue is the element of the numbersArr array being processed. Here, currentValue is added to the accumulator, and the return value is supplied as an argument the next time the callback function is called.
const numbersArr = [67.90.100.37.60];
const total = numbersArr.reduce(function(accumulator, currentValue){
console.log("accumulator is " + accumulator + " current value is " + currentValue);
return accumulator + currentValue;
}, 0);
console.log("total : "+ total);
Copy the code
The output
accumulator is 0 current value is 67
accumulator is 67 current value is 90
accumulator is 157 current value is 100
accumulator is 257 current value is 37
accumulator is 294 current value is 60
total : 354
Copy the code
JavaScript to reduce the use case
1. Sum all the values of the array
In the code below, the studentResult array has five numbers. Use the reduce() method to reduce the array to a single value that assigns all the values and results of the studentResult array to Total.
const studentResult = [67.90.100.37.60];
const total = studentResult.reduce((accumulator, currentValue) = > accumulator +currentValue, 0);
console.log(total); / / 354
Copy the code
2. Sum of values in an object array
Typically, we get data from the back end as an array of objects, so the Reduce () method helps manage our front-end logic. In the following code, currentValue.marks takes the score for each of the three subjects in the studentResult array.
const studentResult = [
{ subject: 'mathematics'.marks: 78 },
{ subject: 'physical'.marks: 80 },
{ subject: 'chemistry'.marks: 93}];const total = studentResult.reduce((accumulator, currentValue) = > accumulator + currentValue.marks, 0);
console.log(total); / / 251
Copy the code
3. Flatten the array
“Flattening an array” refers to converting a multidimensional array to a one-dimensional array. In the code below, the twoDArr 2-dimensional array is converted to an oneDArr 1-dimensional array. Here, the first [1,2] array is assigned to the accumulator, and then every remaining element of the twoDArr array is attached to the accumulator.
const twoDArr = [ [1.2], [3.4], [5.6], [7.8], [9.10]].const oneDArr = twoDArr.reduce((accumulator, currentValue) = > accumulator.concat(currentValue));
console.log(oneDArr);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Copy the code
4. Group objects by properties
We can use the reduce() method to divide an array of objects into groups based on their properties. You can see this concept clearly in the following code snippet. Here, the Result object array has five objects, each with subject and Marks attributes. If the score is greater than or equal to 50, the topic passes, otherwise, the topic fails. Reduce () is used to group results into pass and fail. First, initialValue is assigned to the accumulator, and then the push() method adds the current object to the Pass and Fail properties as an array of objects after checking the conditions.
const result = [
{subject: 'physical'.marks: 41},
{subject: 'chemistry'.marks: 59},
{subject: 'Advanced Mathematics'.marks: 36},
{subject: 'Applied Mathematics'.marks: 90},
{subject: 'English'.marks: 64},];let initialValue = {
pass: [].fail: []}const groupedResult = result.reduce((accumulator, current) = > {
(current.marks >= 50)? accumulator.pass.push(current) : accumulator.fail.push(current);return accumulator;
}, initialValue);
console.log(groupedResult);
Copy the code
The output
{
pass: [{subject: chemistry,marks: 59 },
{ subject'Applied Mathematics',marks: 90 },
{ subject'English',marks: 64}].fail: [{subject'Physics',marks: 41 },
{ subject: advanced Mathematics,marks: 36}}]Copy the code
5. Delete duplicates from the array
In the code snippet below, duplicate items in the plicatedArr array are removed. First, an empty array is assigned to the accumulator as its initial value. Accumulator.includes () checks whether each element of the duplicatedArr array is already available in the accumulator. If currentValue is not available in the accumulator, it is added using push().
const duplicatedsArr = [1.5.6.5.7.1.6.8.9.7];
const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) = > {
if(! accumulator.includes(currentValue)){ accumulator.push(currentValue); }returnaccumulator; } []);console.log(removeDuplicatedArr);
// [1, 5, 6, 7, 8, 9]
Copy the code
conclusion
In this article, we discussed the array reduce() method. The reduce() method is introduced first, followed by a simple example to discuss its behavior. Finally, the five most common use cases for the Reduce () method are discussed through examples. If you are new to JavaScript, this article will help you.
Source: medium.com/javascript-… , written by Wathsala Danthasinghe, translated by Public account front-end Full Stack Developer