Master the Javascript Array Reduce Method with 10 Examples
Tags: beginners, javascript, webdev, programming
Published: 2021-09-20 17:03:06

The Javascript reduce method is a powerful tool that allows developers to iterate over an array and accumulate a single value or object. In this tutorial, we will learn how to use the reduce method to solve real-world problems, from simple summations and multiplications to advanced tasks such as removing duplicates from an array and validating parenthesis.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfq63k5midy69c78cjno.png)

By the end of this tutorial, you will have a solid understanding of how to use the reduce method and will be able to apply it to your own projects with confidence.


## 1. Summation and Multiplication:
The reduce is perfect for performing simple mathematical operations on an array. For example, we can use the reduce method to find the sum or product of all the elements in an array.

{% katex inline %}
\sum and \prod
{% endkatex %}
```javascript
// Summation
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i);

// Without initial value
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a + i, 5 );

// For clarity the above code is the same as 
[3, 5, 4, 3, 6, 2, 3, 4].reduce(function(a, i){return (a + i)}, 0 );

// Multiplication
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => a * i);
```
In this example we can leave the initial value out, as it will grab the first item in the array, but you can also specify one to have an offset.

## 2. Find the maximum in an array:
Another common use case for the reduce method is finding the maximum value in an array. By specifying an initial value of -Infinity, we can compare each element in the array to the accumulator and return the maximum value.
```javascript
[3, 5, 4, 3, 6, 2, 3, 4].reduce((a, i) => Math.max(a, i), -Infinity);
```

As an alternative you could use the spread operator and Math.max built-in method as well.
```javascript
Math.max(...[3, 5, 4, 3, 6, 2, 3, 4]);
``` 

## 3. Concatenating uneven arrays
The reduce method can also be used to concatenate arrays, even if they are of different lengths. In this example, we use the map method to iterate over each sub-array, and then use the reduce method to combine all the elements into a single string.
```javascript
let data = [
  ["The","red", "horse"],
  ["Plane","over","the","ocean"],
  ["Chocolate","ice","cream","is","awesome"], 
  ["this","is","a","long","sentence"]
]
let dataConcat = data.map(item=>item.reduce((a,i)=>`${a} ${i}`))

// Result
['The red horse', 
'Plane over the ocean', 
'Chocolate ice cream is awesome', 
'this is a long sentence']
```

## 4. Removing duplicates in an array:
The reduce method can also be used to remove duplicates from an array. In this example, we check if the current value has an index in the accumulator array. If not, we add it to the array.
```javascript
let dupes = [1,2,3,'a','a','f',3,4,2,'d','d']
let withOutDupes = dupes.reduce((noDupes, curVal) => {
  if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
  return noDupes
}, [])
```
It's important to note that this method can also be achieved by using [javascript set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set), which by default store only unique values.

## 5. Validating parenthesis
The reduce method can also be used to validate parenthesis in a string. In this example, we use the spread operator to convert the string into an array, and then use the reduce method to iterate over each character. If the character is an opening parenthesis, we increment the accumulator, and if it's a closing parenthesis, we decrement it. In the end if the status is 0, the parenthesis are balanced.

```javascript
[..."(())()(()())"].reduce((a,i)=> i==='('?a+1:a-1,0);

// using a for loop
status=0
for i in string:
  if(i=="("):
    status=status+1
  elif(i==")"):
    status=status-1     
  if(status<0):
    return False
```

## 6. Filtering and Counting:
The reduce method can also be used to filter and count elements in an array. In this example, we use the reduce method to filter out all elements that are not a number, and then count the number of remaining elements.

```javascript
let data = [1, 2, "a", "b", 3, "c", 4, "d"];
let filteredData = data.reduce((acc, curr) => {
  if (typeof curr === "number") {
    acc.push(curr);
  }
  return acc;
}, []);
console.log(filteredData); // [1, 2, 3, 4]
console.log(filteredData.length); // 4
```

## 7. Group by property
The reduce method can also be used to group elements in an array by a specific property. In this example, we use the reduce method to group an array of objects by their "type" property. In each iteration, we check if the key exist if not we create an array, then we add the current type to that and we return the group array.

```javascript
let data = [
  { type: "A", value: 1 },
  { type: "B", value: 2 },
  { type: "A", value: 3 },
  { type: "B", value: 4 },
  { type: "A", value: 5 },
];
let groupedData = data.reduce((acc, curr) => {
  if (!acc[curr.type]) {
    acc[curr.type] = [];
  }
  acc[curr.type].push(curr);
  return acc;
}, {});
console.log(groupedData); // { A: [ { type: 'A', value: 1 }, { type: 'A', value: 3 }, { type: 'A', value: 5 } ], B: [ { type: 'B', value: 2 }, { type: 'B', value: 4 } ] }
```

## 8. Flattening a Nested Array:
The reduce method can also be used to flatten a nested array. In this example, we use the reduce method to flatten an array of arrays into a single array.

```javascript
let data = [[1, 2], [3, 4], [5, 6]];
let flattenedData = data.reduce((acc, curr) => acc.concat(curr), []);
console.log(flattenedData); // [1, 2, 3, 4, 5, 6]
```

An intended way of doing this is just to use the .flat method.
```javascript
[ [3, 4, 5],
  [2, 5, 3],
  [4, 5, 6]
].flat();
```
## 9. Counting Occurrences of Elements:
In this example, we use the reduce method to count the occurrences of each element in an array.

```javascript
let data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
let countedData = data.reduce((acc, curr) => {
  if (!acc[curr]) {
    acc[curr] = 0;
  }
  acc[curr]++;
  return acc;
}, {});
console.log(countedData); // { 1: 1, 2: 2, 3: 3, 4: 4 }
```
This one is like doing a map and a filter at the same time, we filter the negative numbers and we rise the positive.

## 10. Reverse a string
Here we use the reduce method to reverse a string, this will work with any object not only strings.

```javascript
const reverseStr = str=>[...str].reduce((a,v)=>v+a)
```
## Bonus
## 11. Binary to decimal
In this example we can use it to convert a binary number to decimal.
Here we convert the string into an array, and we square in order the array until we have the decimal number.

```javascript
const bin2dec = str=>[...String(str)].reduce((acc,cur)=>+cur+acc*2,0)

// Long format for readability
const bin2dec = (str) => {
  return [...String(str)].reduce((acc,cur)=>{
    return +cur+acc*2
  },0)
}
```
To Illustrate this one let's see an example:
(10111)->1+(1+(1+(0+(1+0*2)*2)*2)*2)*2

And we reach the end, the reduce method is a versatile and powerful tool that can be used to solve a wide range of problems. 

Check out my youtube channel [ramgendeploy](https://www.youtube.com/c/ramgendeploy) drop a sub if you like there 😄