DEV Community

Hardeep Singh
Hardeep Singh

Posted on

3 1

Practical use of array.reduce() in JavaScript

Alt Text

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);
Enter fullscreen mode Exit fullscreen mode

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

For example : Following are valid 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")
Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay