How to use Javascript Reduce for array of objects? In this article, we will use an array.reduce javascript for this. We will learn this step by step in this article. Sometimes we need to reduce an array to a single value (Javascript Primitive Types) like a number, boolean, string, object or another array. In order to do that we can use the javascript array reduce method. The array reduce in JavaScript is a predefined array method which executes a callback function which is known as the reducer. This callback function executes on each element of the array resulting in a single output value.
Also, this execution is occurring in the left-to-right sequence. Also, this javascript array reduce (also known as Higher Order Functions) is a non-mutating method. That means instead of changing the actual value in the array it can hold the computed value in the accumulator without changing the original value.
How to use Javascript Reduce for array of objects basics
So Let’s dive into some examples for array.reduce javascript and We will go from easy to advanced. First, let’s think about an array of items. Each item has a name and price. we need to calculate the total price of the items. So how we are going to do that? The one method which comes to our mind is using forEach function. Let’s see how we can get the total.
So as you can see we can use the forEach function in javascript to calculate this like above. We can use Array.reduce function to do this as well. Let’s first see what the arguments that we are going to pass into this.
Array.reduce syntax
array.reduce(callbackfn(total, currentValue, curIndex, array), initialValue)
Simply it accepts 2 parameters. Callback Function and the initial value which is the starting value.
- Callbackfn: This is a required parameter that holds the function that is supposed to be executed on every array item. Also, it accepts 4 parameters.
- total | Required: This is the accumulator. This holds the initial value if it is provided in the reduce function or the previously returned value from the callback function.
- currentValue | Required: This holds the current item which is executing.
- curIndex | Optional: This holds the index of the current value
- array | Optional: This is the complete array object which the reduce() was called
- initialValue | Optional: This is the initial value to be passed into the reduce function. If no initial value is supplied the first value in the array is used as the initial accumulator and the second element of the array becomes the current value(currentValue). If you use array reduce on an array without any items and do not provide initialValue. It will always throw a TypeError.
Let’s look at how we can implement the above forEach example with the javascript array.reduce function.
So as you can see the total is the accumulator which we reducing our value down to. For every iteration, we are returning the total value. The final output will be the total price of the items. This will be useful in scenarios like calculating item prices in a shopping cart.
So let’s have a look for more examples of JavaScript Reduce for Array of Objects.
Examples
1. Flattening an Array of Arrays With Javascript Reduce Method
We can use reduce method to flatten arrays of array(flatten to a single array) using the javascript array.reduce method. Let’s check the example for that.
So in this here we have set the default output reduced value to an empty array because we want the final output to be an array. Then on each item, we do concat with the currentVal. On the first iteration what happens is an empty array([]) is assigned to flattenArray. and current Value is the first item in the array which is also another array. so we concat that. Like that, it will go throughout all the items. Finally, the output will be one array like this.
2. Group objects with Javascript Reduce Array
Here you can see that we have set the initial value to an empty object. Because we want the final output grouped with the age. So the output for this will be like this. peopleGroupedByAge is the accumulator which is nothing but the calculated grouped object. At the first iteration, its value is {}. Then we first check if there is a value for a particular age group. If there is not we first initialize an empty array for that particular age group. Then we push the curValue(current item) to that initialized age group. So like that, we can create a grouped object with age as the key value for the object. Here is the console output.
3. Remove duplicates with Javascript Array Reduce
For this also as you can see we need an array as the final output. So let’s think about the first iteration of this. In the first iteration, we check if the index of the first item is in the accumulator. At the first iteration, it will return -1. So we push the item to the accumulator. For that if the index of the current Item is there on the accumulator that current item will not be pushed to the accumulator. So it will prevent adding duplicate values to the array. Here the output will be like below.
In this article, you have learned the fundamentals of reduce function and its usage for our real-world scenarios. So if you have any questions or queries please add a comment or contact us via mail at [email protected].
Leave A Comment