## DEV Community is a community of 724,883 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Hardeep Singh

Posted on

# Practical use of array.reduce() in JavaScript ### Definition

The reduce() method executes a reducer function for each value of an array. reduce() returns a single value which is the function's accumulated result.

### How reduce works:

``````var numbers=[10,20,30];

var sumofAllNumbers=numbers.reduce(function(sum,number){
return sum+number;
},0);

console.log(sumofAllNumbers);
``````

reduce() has two parameters

1. reducer/iterator function e.g function(sum,number)
2. Initial value 0 in this case (optional)

reduce() method will iterate over each number and add it to sum variable as shown in example.
*initial value=0
*iteration 1 : sum=10
*iteration 2 : sum=30
*iteration 3 : sum=60
*return 60 to sumofAllNumbers variable

### Practical Example

#### To Balance Parenthesis

1. ()()()
2. ((()))
##### Invalid parenthesis
1. (()))
2. )()
``````function balanceParenthesis(string) {
if (string.length > 0) { // Check input is valid string
return string.split("")
.reduce(function(counter, char) {
if (counter< 0)// special case when we have ) at start
return counter;
if (char === "(")
++counter;
else
--counter;
return counter
}, 0);//counter as initial value
}
return -1;
}

//if functions return 0 then Parenthesis are balanced
if (balanceParenthesis("()()()") == 0)
console.log("Parenthesis are balanced")
else
console.log("Parenthesis are not balanced")
``````

First we converted provided input to array using string.split("")
Then we applied reduce function to iterate over each character

In reduce method we checked if character is '(' then we increased counter value by 1
other wise decreased the value by -1 for ')'

Special check if(counter< 0) added to check cases like ")(" as we will have counter value 0 in this case

So in result if the counter value is 0 then parenthesis are balanced otherwise these are not.