Categories
HTML/Javascript

JavaScript Reduce Method Examples

The JS reduce() method can be difficult to understand because it works recursively.

We’ll go through a few examples of how to use the reduce() function in order to get a grip on it.

Sum With Reduce

Summing with reduce is one of the most common tasks, and it can easily be done on an array.

With reduce you recursively pass the previous result along with the current result to a function. By default the previous result begins at zero.

You can quickly sum an array like this Example:

total = [1,2,3,4,5].reduce((prev, curr) => prev += curr)
console.log(total)
// 15

Average With Reduce

Averaging with reduce is another common task, and you can do this easily by adding then dividing by the length.

class CustomError extends Error{
    constructor(msg) {
        super(msg);
        this.name = "CustomError"
    }
}

throw new CustomError("This is my custom error")
// CustomError: This is my custom error

Reduce An Array Of Objects

Summing up numbers of an object can also similarly be done by adding the value key, you will need to enter a starting value otherwise you will get an odd result.

objects = [
    {name: "first",
    value: 1},
    {name: "second",
    value: 2},
    {name: "third",
    value: 3}
]
total = objects.reduce((prev, curr) => prev += curr.value, 0)
console.log(total)

Create An Object With Reduce

Creating objects with reduce can also be done quite easily using the ES6 spread syntax ellipsis operator (…) like in this example.

objects = [
    {
        name: "first",
        value: 1
    },
    {
        name: "second",
        value: 2
    },
    {
        name: "third",
        value: 3
    }
]
summaryObject = objects.reduce((prev, cur) => {
    return {...prev, [cur.name]: cur.value }
}, {})
console.log(summaryObject)

Notice that we needed to pass in an empty object for the starting value.

Create An Array With Reduce

Creating arrays with reduce is also easy using the spread syntax and we can do it in one line like in this example.

objects = [
    {
        name: "first",
        value: 1
    },
    {
        name: "second",
        value: 2
    },
    {
        name: "third",
        value: 3
    }
]
summaryArray = objects.reduce((prev, cur) => [...prev, cur.name], []
)
console.log(summaryArray)

Reduce From Right To Left

If you’re looking to reduce from right to left you can use the reduceRight() method.

objects = [
    {
        name: "first",
        value: 1
    },
    {
        name: "second",
        value: 2
    },
    {
        name: "third",
        value: 3
    }
]
reverseSummaryArray = objects.reduceRight((prev, cur) => [...prev, cur.name], []
)
console.log(reverseSummaryArray)
// [ 'third', 'second', 'first' ]

Conclusion

The reduce() method is very handy and can help you to avoid using a lot of for loops.

It may be difficult to grasp at first if you’re not used to recursive thinking, but eventually it will feel natural.

You might be wondering why we didn’t show examples using reverse to perform tasks such as filtering an array, and that’s because with ES6 the some() every() and filter() methods were added to JavaScript making those tasks easier than using reduce.

Exit mobile version