0

I am using reduce() in one of my functions to get a single value from some documents. Generally, this works as expected. However, once in a while I get an error "reduce is not a function". I know that, according to the docs, "Calling reduce() on an empty array without an initial value is an error" -- so I am passing "0" to handle that. But I still sometimes - though rarely - get the error. Just trying to understand what's going on.

My code looks like this:

 let totalOpenBalance = docs.reduce((a, curr) => a + curr.openBalance, 0);

The data I'm calling this on looks like this:

[
    {
        "_id": "3s14020471287f4a9bbe9878",
        "openBalance": 120,
        "field3": 25
    },
    {
        "_id": "2d75020471986f4a9bbe7231",
        "openBalance": 15,
        "field3": 22
    }
]
0

1 Answer 1

2

The error message “reduce is not a function” has nothing to do with the arguments you pass to reduce – it is referring to the docs.reduce part of your code. This error message happens when the reduce property of docs is not a function as expected, but some other type of value such as undefined.

Since all arrays have a reduce function, that means that sometimes your docs variable is not an array. Add console.log(docs) before that line to see what type it is, and check where it is assigned to see why it is the wrong type.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, interesting. I'll have to think through under what circumstance "docs" would not be an array. Even an array of 1 element should be fine, correct?
@Muirik Yes, an array with any number of elements including 1 or 0 would still have a reduce function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.