Reduce in JavaScript

Reduce in JavaScript

What is the reduce() function in JavaScript?

reduce() is a Higher Order function in JavaScript

Higher order functions

In Javascript, functions can be assigned to variables in the same way that strings or arrays can. They can be passed into other functions as parameters or returned from them as well. A “higher-order function” is a function that accepts other functions as parameters and/or returns a function as a value.

The reduce() iterates through the array and returns a single value. The returned value can be a number, string, array or object.

The reduce() method executes a reducer (callback) function for an array element.

The reduce() method returns a single value: the function's accumulated result.

The reduce() method does not execute the function for empty array elements.

The reduce() method does not change the original array.

Reduce Syntax

reduce takes a callback function with parameters ( accumulator , currentValue, currentIndex, array ) as arguments. It also takes an optional initialValue as a parameter.

arr.reduce((accumulator, currentValue, currentIndex, array) => {  
// some operations goes here before returning a value 
return value
}, initialValue)
  • accumulator: It is a required parameter, that holds the initialValue in the beginning and then the last returned value of the function.

  • currentValue: This is a required argument that holds the value of the current element being executed.

  • currentIndex: It is an optional parameter holding the index of the current value.

  • array: This is also an optional parameter that holds the complete array object on which the operation is performed.

  • initialValue: This is an optional parameter and holds the initial value passed to the function.

How does reduce work?

Let's understand how reduce works with the following examples.

Example 1: Get the sum of the numbers array

// get the sum of numbers array using reduce 
const numbers = [10, 20, 30, 40, 50]
const sum = numbers.reduce((acc, curr) => acc + curr, 0)

console.log(sum)
// Output: 150

In the above code box, we use reduce function on the numbers array to get the sum of all the numbers in the array. In the callback function, we have accumulator (acc) and current value (curr) as parameters and return (acc+curr) after every iteration. The Initial Value is defined as 0.

When the function starts the accumulator value is the initialValue that is 0.

  1. In the first iteration, the current value (curr) is 10, the accumulator value (acc) is 0 and the current value gets added to the accumulator. So the accumulator value becomes 10.

  2. In the second iteration, the current value (curr) is 20, the accumulator value (acc) is 10 and the current value gets added to the accumulator. So the accumulator value becomes 30.

  3. In the third iteration, the current value (curr) is 30, the accumulator value (acc) is 30 and the current value gets added to the accumulator. So the accumulator value becomes 60.

  4. In the fourth iteration, the current value (curr) is 40, the accumulator value (acc) is 60 and the current value gets added to the accumulator. So the accumulator value becomes 100.

  5. In the fifth iteration, the current value (curr) is 100, the accumulator value (acc) is 50 and the current value gets added to the accumulator. So the accumulator value becomes 150. After the fifth and last iteration, the acc value is returned.

And Hence we get the sum of 150 as Output.

Example 2: Get the minimum number from the numbers array

// get the minimum number of numbers array using reduce 
const numbers = [10, 5, 8, 3, 6];
const getMinimumNumber = array => array.reduce((acc,curr)=>(curr<acc ?acc=curr :acc));
console.log(getMinimumNumber(numbers)); 
// Output: 3

In the above code box, we use reduce function on the numbers array to get the minimum number of all the numbers in the array. In the callback function, we have accumulator (acc) and current value (curr) as parameters and check if the accumulator is smaller than the current value, if the condition is true that is if the current value is smaller than the accumulator, the current value will become the accumulator and if the condition is false that is if the accumulator is smaller than the current value, the accumulator will stay as it is and it will not change after every iteration. The Initial Value is undefined as we want the accumulator to take the first value of the array.

When the function starts the accumulator value is the first value of the array that is 10.

  1. In the first iteration, the current value (curr) is 10, accumulator value (acc) is 10, as the initial value is undefined, the first current value (first value in the array) becomes the accumulator and the current value gets compared to the accumulator. So the accumulator value becomes 10.

  2. In the second iteration, the current value (curr) is 5, the accumulator value (acc) is 10 and the current value gets compared to the accumulator. According to the condition, the smaller value gets returned as the accumulator value. So the accumulator value becomes 5.

  3. In the third iteration, the current value (curr) is 8, the accumulator value (acc) is 5 and the current value gets compared to the accumulator. And the smaller value gets returned as the accumulator value. So the accumulator value remains 5.

  4. In the fourth iteration, the current value (curr) is 3, the accumulator value (acc) is 5 and the current value gets compared to the accumulator. And the smaller value gets returned as the accumulator value. So the accumulator value becomes 3.

  5. In the fifth iteration, the current value (curr) is 6, the accumulator value (acc) is 3 and the current value gets compared to the accumulator. And the smaller value gets returned as the accumulator value. So the accumulator value remains 3. After the fifth and last iteration, the acc value is returned.

And Hence we get the minimum number that is 3 as Output.

Good practices while using reduce

  1. Know what type of value you want to return. Whether you want a Number, String, Array or Object.

  2. Based on the type of value you want to return, Define the initial value. Even though the Initial value is optional it is a good practice to define the Initial value. If we do not specify the initial value, by default accumulator will get the array’s first value. If our array is an empty array, then Javascript will throw an error.

  3. When you want to return an array, It is better to use the array spread method and .concat based on the use case instead of .push, as .push mutates the existing array.

Benefits of using reduce

reduce() provides a cleaner way of iterating over and reducing values in an array instead of using a for loop. It also helps in reducing the code complexity and makes the code more readable.

reduce() function can be used to perform complex operations on an array like finding the sum, product, minimum, maximum and average of the array elements. It also helps in transforming an array of objects into a single object or an array of some other type.

Browsers Supporting Array Reduce in JavaScript

The following list of browsers supports the use of array reduce in JavaScript:

  • Google Chrome

  • Microsoft Edge 9.0

  • Mozilla Firefox 3.0

  • Safari 5.0

  • Opera 10.5

Conclusion

The reduce() function is a powerful tool in JavaScript that can help you perform complex operations on arrays in a more concise and readable way. By understanding the syntax and how it works, you can use reduce() to simplify your code and perform a wide range of operations on your data.

References

https://github.com/Asabeneh/30-Days-Of-JavaScript/blob/master/09_Day_Higher_order_functions/09_day_higher_order_functions.md

https://www.simplilearn.com/tutorials/javascript-tutorial/array-reduce-javascript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce