DEV Community

Cover image for What is array.reduce() in JavaScript ?
Noa
Noa

Posted on

What is array.reduce() in JavaScript ?

Reduce example overview

Reduce is an array method that can convert or reduce the data in an array and return a single output.

Syntax:

array.reduce( reducerfunction ( accumilator, item, index, array ), initalAccumilatorValue )
Enter fullscreen mode Exit fullscreen mode
  • accumulator is a variable that will be changed in each loop through the array.
  • item refers to the current item in the array.
  • index refers to the index of the current item in the array.
  • array refers to the initial array.
  • reducer function shows how the accumulator is modified.

Where would we use reduce?

Consider we have an input array containing information about users, ie name, age, etc, and had to group them by age.

    const array = [
        { name: "John", age: "20" },
        { name: "Mary", age: "20" },
        { name: "Peter", age: "50" },
        { name: "Sally", age: "50" },
    ];

Enter fullscreen mode Exit fullscreen mode

if we had to group them by age.

    {
        20: ["John","Mary"],
        50: ["Peter","Sally"]
    }

Enter fullscreen mode Exit fullscreen mode

we could use the array.reduce() method.


    const result = array.reduce((acc, curr) => {
    if (!acc[curr.age]) { //chk if age exist in accumilator
        acc[curr.age] = []; //createing empty array at accumelator.age
    }
    acc[curr.age].push(curr.name); // pushing name to appropriate accumulator.age
    return acc;
    }, {});

    console.log(result);

Enter fullscreen mode Exit fullscreen mode

How does it work?

when we call the array.reduce() method we pass two parameters.

  1. accumulator function
  2. initial value for the accumulator

The accumulator function defines what action needs to take place to a value( the accumulator ) so that the desired final reduced value may be obtained

in the above example

Reduce example explanation

Every element is passed one by one to the accumulator function, Which checks if the age of the given person is not already present in the accumulator, If that is the case, Then it creates a new property for the person's age and assigns an empty list to it. later the person's name is pushed to the property where their age is present ( either newly created or previously present )

Conclusion

The array.reduce() method is a very powerful array method that could simplify complex loop logic and provide a much more intuitive programming experience to the developer and the reader.

Top comments (1)

Collapse
 
jovylle profile image
Jovylle B

nice