reduce in javascript

What is Reduce in JavaScript and the Best 10 Examples

The Reduce in JavaScript is a type of built-in function that allows the user to apply the function callback for each array element, and convert it to a unit value. This method has very significant capabilities in the JavaScript programming language and is used in various scenarios. In this article from Thinkwriteway.com Technology Blog, the question of what the Reduce method in JavaScript is answered, and several practical examples are also provided for better understanding.

What is the Reduce method in JavaScript?

The Reduce method in JavaScript is considered a fundamental aspect of “Functional Programming”. This method processes the elements in the array from left to right and stores the resulting value in an “Accumulator”.

Importantly, reduce is a no-mutation method, meaning it does not modify the original array or its elements. Instead, it calculates the desired value as appropriate for the operation and stores it in the accumulator, while leaving the original variables unchanged. This powerful feature enables JavaScript programmers to convert an array to a single value while preserving the integrity of the original data.

Syntax of Reduce in JavaScript

The “Syntax” of the Reduce method in Javascript is the following code snippet:

array.reduce(callbackfn(total, curValue, curIndex, array), initialValue)

In the following, each of the implementations of the Reduce in JavaScript syntax is described in the form of a list.

  • Callbackfn: It is considered a kind of mandatory parameter that indicates a function that should be executed on each element of the array. This parameter requires the following 4 arguments:
  • Total: This is a mandatory parameter that initially values initialValue holds and then stores the last return value from the function.
  • CurValue: This parameter is also mandatory and holds the value of the current element being processed.
  • curIndex: This is an optional parameter that holds the index of the current value being processed.
  • array: This is also an optional parameter and represents the complete object of the array on which the operation is performed.
  • initialValue: is also an optional parameter that holds the initial value sent to the function.
reduce in javascript

By understanding and using the reduce in javascript method With its appropriate command and parameter values, it is possible to perform powerful operations on arrays in JavaScript.

The Concept of Reducer and Accumulator

The terms “Reducer” and “Accumulator” are key concepts when working with the Reducer method in JavaScript.

  • Reducer: means reducer or reducer and refers to the operation or action that is applied to each element of the array during the Reduce process. In fact, Reducer is responsible for reducing the entire array to a single value by executing a specific function on each element.
  • Accumulator: This term also means accumulator and is an important component in the method Reduce Is. The accumulator actually represents a variable or a container that holds the intermediate and final results by applying the reducing function to each element of the array. Initially, the accumulator may have an optional initial value and then store the last value returned from the decrement function.

Understanding the roles of reducer and accumulator is very important when using the Reducer method in JavaScript. By defining the appropriate reducer function and managing the accumulator effectively, powerful operations can be performed.

Reduce features in JavaScript

The Reduce method in JavaScript has the following features:

  • Providing an initial value: If an initial value is specified, the accumulator will be set to that value and curValue will be equal to the first value of the array.
  • Failure to provide the initial value: If the value initialValue or the same initial value is deleted, the accumulator is set to the first element of the array and initialValue It will be equal to the value of the second element.
  • Management of empty arrays: If reduce() is applied to an empty array without providing an initial value, TypeError will be created.
  • non-implementation callbackfn For empty or single-element arrays: if the array is empty and FillValue provided, or if the array contains only one element plus initialValue be, method reduce() Simply the same value without executing the function callback returns.

Understanding these features helps the programmer to effectively use the method reduce() and enables him to manage different scenarios.

Example of Reduce in JavaScript

In the above section, the syntax of the Reduce method in javascript and its mission in JavaScript coding were explained. In this section, for a better understanding, the concept of reduction is presented in the form of several examples with relevant explanations.

Example of summing all array values ​​with Reduce in Javascript

In the following example, using Reduce in JavaScript, all elements of the array will be added together, and the result will be recorded in the console.

let num = [5, 9, 12, 24, 67]

let sum = num.reduce(function (accumulator, curValue) {

  return accumulator + curValue

}, 0)

console.log(sum)

Now, by running the above code in the console, the output will be displayed as follows:

117

The above codes can also be written with “Arrow Functions” as follows, the output of which is the same as the output of the above code.

let num = [5, 9, 12, 24, 67]

let sum = num.reduce((accumulator, curValue) => accumulator + curValue, 0)

console.log(sum)

Example of summing the values ​​in the array using Array Reduce

To calculate the sum of values ​​from an array of objects, an initial value for the method is required Reduce()  Submitted. By doing this, all elements of the array are processed by the function and the desired result is obtained. The code fragment of the mentioned example is as follows:

let initialValue = 0

let obj = [{n: 5}, {n: 9}, {n: 13}, {n: 25}, {n: 40}]

let sum = obj.reduce(function (accumulator, curValue) {

    return accumulator + curValue.n

}, initialValue)

console.log(sum)

By running the above code in the console, the output will be displayed as follows:

92

An example of flattening an array of arrays with the Reduce method in JavaScript

Consider a scenario where there is an array of arrays and the goal is to flatten it into a single array. The following code shows how to achieve this goal using the Reduce method in Javascript:

let mulArray = [[3, 5], [1, 7], [12, 9]]

let newArray = mulArray.reduce(function(accumulator, curValue) {

    return accumulator.concat(curValue)

  },[]

)

console.log(newArray)

By running the above code in the JavaScript console, the output will be as follows:

(6) [3, 5, 1, 7, 12, 9]

In the above example, the variable mulArray  An array consists of several arrays. In the codes above, the method Reduce()  To mulArray is applied and the function will be passed as the first argument. This function callback  Two parameters accumulator  And curValue  accepted in the function callback , from the method concat()  For array concatenation curValue It is used with the accumulator array, which will make the desired flat array.

The second argument passed to Reduced()empty array []  which acts as the initial value of the accumulator. This argument will ensure that the first iteration starts with an empty array. Finally, the resulting flat array in variable newArray  will be saved and recorded in the console.

An example of counting instances in an object using Reduce in Javascript

In this example, an array named myCars  There are different car names. In this example, the Reduce method in JavaScript will be used to count the number of times each car name appears in the array. Its code fragment is as follows.

let myCars = ['Mercedes-Benz', 'Jeep', 'Ferrari', 'Lamborghini', 'Mercedes-Benz', 'BMW', 'Ferrari']

let instances = myCars.reduce(function (allCars, car) {

  if (car in allCars) {

    allCars[car]++

  }

  else {

    allCars[car] = 1

  }

  return allCars

}, {})

console.log(instances)

By executing the above code, the output in the console will be as follows:

{Mercedes-Benz=2,  Jeep=1, Ferrari=2,  Lamborghini=1, BMW=1}

BMW=1
Ferrari=2
Jeep=1
Lamborghini=1
Mercedes-Benz=2

In the above code, the method Reduce()  To myCars  Actions and follow callback  is Passed as the first argument. Also, function callback Two parameters allCars  And car  takes

Inside the function callback, using the operator in  Checks if the vehicle is already a feature in the object allCars has it been or not, and if so, the number related to the car in question will be increased. If not, to the object allCars is added and the number on 1  will put

The second argument passed to Reduced()  empty object {}  is as the initial value for the object allCars it works. Finally, the obtained object with the number of car names is stored in the instances variable and recorded in the console.

An example of grouping objects with Reduce in JavaScript

In the following example, an array named student There are objects that represent students. Now, if you want to group these objects based on the value of a certain property using the Reduce method in JavaScript, you should do the following:

let student = [

  { name: 'David', age: 23, hobby: 'fishing' },

  { name: 'Rachel', age: 25, hobby: 'cooking' },

  { name: 'Rahul', age: 22, hobby: 'fishing' }

];

function myFunc(obj, prop) {

  return obj.reduce(function (acc, item) {

    let key = item[prop]

    if (!acc[key]) {

      acc[key] = []

    }

    acc[key].push(item)

    return acc

  }, {})

}

let groupedStudent = myFunc(student, 'hobby')

console.log(groupedStudent)

The output of the above code fragment by running it in the console will be as follows:

reduce in javascript

In the above code, a function called groupObjectsByProperty  is defined as an array obj  , and the feature prop  is taken as a parameter. Inside the function, the method Reduce()  on the array obj Applied. Function callback Also 2 parameters acc (accumulator)  And item  takes

in the function callback , attribute value prop Extract from any object and into variable key  assigned If key as a property on the object acc  If it does not exist, it will be initialized as an empty array. then the current item into the array key The corresponding push will be given. Finally, object acc It is returned that now contains the objects grouped by the specified property value.

An example of removing duplicates with the Reduce method

This example is about removing duplicates using the Reduce method in JavaScript. In the example below, working with an array named array  initialized which will contain multiple duplicate values. The goal is to remove duplicate values ​​using the Reduce method in Javascript, the code snippet for doing this is given below.

let array = [2, 5, 7, 5, 12, 9, 7, 5, 4, 3, 5, 2, 4, 15]

let newArray = array.reduce(function (accumulator, curValue) {

  if (accumulator.indexOf(curValue) === -1) {

    accumulator.push(curValue)

  }

  return accumulator

}, [])

console.log(newArray)

By running the above code in the JavaScript console, the output will be as follows:

(8) [2, 5, 7, 12, 9, 4, 3, 15]

In the code snippet above, the method Reduce()  to the array of actions and functions callback is Passed as the first argument. Inside the function callback , using the method indexOf()‎  It is checked whether CurValue  in the array accumulator  exists or not, and if not (returns -1), CurValue pushes to the accumulator array.

The second argument passed to Reduce() empty array []  which serves as the initial value for the accumulator. This array will also ensure that the first iteration starts with an empty array. Finally, the resulting array without duplicate values ​​in the variable newArray  It will be saved and registered in the console.

Reduce in JavaScript ES5

Reduce is used in JavaScript “ES5” as follows:

var euros = [29.76, 41.85, 46.5]; 

var sum = euros.reduce( function(total, amount){
  return total + amount
});

sum // 118.11

In the above example instead of keyword was  From const  used and after the parameters, the expression function  With “fat arrow” (=>)  Substitution and expression return  were removed from it. This is the way to write the Reduce method in ES5, and yet the ” JavaScript ES6 ” syntax for this purpose will be more concise and less error-prone.

How to find the average with the Reduce method in JavaScript?

To find the average instead of the total sum of the array elements, the total value can be divided by the length of the array before returning the final value. In JavaScript’s Reduce method, additional arguments can be used.

The first argument index  indicates the number of times the function Reducer  Iterates through the array. The following example shows this.

const euros = [29.76, 41.85, 46.5];

const average = euros.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length-1) { 
    return total/array.length;
  }else { 
    return total;
  }
});

average // 39.37

Map and Filter as a reduction in JavaScript

In the previous example, the Reduce function was used to calculate the average, now it can be used in different ways according to the needs of the program.

For example, you can double the sum or halve each number before adding them. You can also use conditional commands inside it to use only certain numbers in the desired operation. Also, many other operations can be performed on it and only some units will be returned. However, the interesting part is that the user is not limited to returning a unit value. It is also possible to convert the array into a new array or reduce it so to speak.

Reduce in javascript

For example, in the following, an array of values ​​will be reduced to another array, where each value of the array will be doubled. To achieve this goal, the accumulator must be initialized, which in this case will be an empty array. The initial value represents the starting value of the total parameter when the reduction operation is started. The initial value can be changed by adding a comma ( ,  ) and then your arbitrary initial value inside the parentheses after {}  set up Just like the example below:

const average = euros.reduce((total, amount, index, array) => {
  total += amount
  return total/array.length
}, 0);

In the previous examples, remove the initial value and replace it with a default value total  was assigned to it. However, when the initial value is set to an empty array, any value can be set to the total Allocated. If the goal is to reduce an array of values ​​to another array where each value is doubled, then the value 2*  to the array total Apply or so-called push. The following example conveys this concept.

const euros = [29.76, 41.85, 46.5];

const doubled = euros.reduce((total, amount) => {
  total.push(amount * 2);
  return total;
}, []);

doubled // [59.52, 83.7, 93]

In the example above, using the Reduce method in JavaScript, a new array was successfully created where each value is doubled. However, one can go a step further and apply filtering to prevent certain numbers from being doubled. This can be done by combining the command if  At Reducer  Did. The following example shows this.

const euro = [29.76, 41.85, 46.5];

const above30 = euro.reduce((total, amount) => {
  if (amount > 30) {
    total.push(amount);
  }
  return total;
}, []);

above30 // [ 41.85, 46.5 ]

The operation ” Map  ” And ” Filter  » can also be achieved using the Reduce method in JavaScript. However, in the case of these examples, use the operation directly Map And Filter It will be easier. The real power of the Reduce method is when the user needs to combine operations Map And Filter especially when the user is dealing with large amounts of data.

When operation Map And Filter are combined, basically the operation will be done 2 times. First, it filters each value, and then the operation Map is done on them. However, with the Reduce method in Javascript, it is possible to perform the mentioned operations at the same time. In simple and trivial examples, due to the increase in code complexity, use the Reduce method to perform operations Map And Filter It is not recommended, but in more complex and combined scenarios, the efficiency of the Reduce method can be used to do this.

Piping with the Reduce method

One of the interesting aspects of the Reduce method in JavaScript is its ability to work not only with numbers and strings but also with functions in JavaScript . Consider a scenario where there is a set of mathematical basis functions.

These functions enable the user to perform operations such as incrementing, decrementing, doubling, and halving a value. The following code snippet illustrates this:

function increment(input) { return input + 1;}

function decrement(input) { return input — 1; }

function double(input) { return input * 2; }

function halve(input) { return input / 2; }

It is assumed that the user wants to increment, double, and then decrement a value. Instead of writing a separate function each time, it can create a reusable “pipeline” using the Reduce method. In this context, a pipeline  is A sequence of functions that transforms an initial value into a final value. pipeline In the hypothetical example of this section, there are three functions of increase, double, and decrease according to the mentioned order.

by using Reduce  , a Can pipeline is created that takes an initial value and will apply each function in sequence, changing the value step by step according to the desired operation. This approach eliminates the need to rewrite functions every time and provides a more flexible and reusable solution.

let pipeline = [increment, double, decrement];

Instead of using the method Reduce In an array of values, the method can be Reduce in pipeline Applied functions. The key aspect of the problem is that the initial value pipeline can be set as the value to be converted as follows.

const result = pipeline.reduce(function(total, func) {
  return func(total);
}, 1);

result // 3

Display advantage pipeline As an array, it is flexible and easy to modify. Considering the pipeline As an array, it is easy to make changes to the sequence of functions. This flexibility allows the programmer to adjust the order or even add or remove functions from the pipeline Customize the conversion process if needed.

For example, if a user’s requirement consists of triple reduction, followed by doubling, reduction again, and finally halving, one can simply pipeline by rearranging the functions accordingly. The following code snippet illustrates this concept:

var pipeline = [

  increment,
  
  increment,
  
  increment,
  
  double,
  
  decrement,
  
  halve
  
];

Common mistakes in using Reduce in JavaScript

One common mistake to avoid when using the Reduce method in the JavaScript programming language is forgetting to pass an initial value. By default, if no initial value is provided, Reduce Assumes the first item in the array as the initial value.

While this may work well in certain cases, it can lead to unexpected results, especially when performing operations such as counting the number of items where an error is likely to occur. Therefore, it is important to ensure that the correct initial value is always used when using Reduce provided to avoid any unexpected behavior.

reduce in javascript

Another mistake to watch out for is forgetting to return the total value in the Reducer function. The reducer function must always return a value for the Reduce method to work properly. Failure to do so can lead to incorrect or unexpected results.

Reduce in JavaScript is supported by which browsers?

Reduce in JavaScript by different browsers such as; Google Chrome, Microsoft Edge 9, Mozilla Firefox 3, Safari 5, and Opera 10.5 will be supported. These browsers have implemented the functions necessary to use the Reduce method on arrays in JavaScript.

Conclusion

The Reduce method in JavaScript is one of the most useful methods used in various scenarios. In this article from “Thinkwriteway Technology Blog” regarding the Reduce method and various aspects of this method, favorable explanations were provided and several practical examples were given along with the explanations.

Also, in this article, training on how to use Pipeline in combination with the Reduce method in JavaScript was presented. In the end, the common mistakes that users may face in using this method were also presented.

If you seek further information about them  or have any inquiries regarding our blog, please don’t hesitate to contact us via email at info@thinkwriteway.com

Share This Article :

Leave a Comment

What to read next