2

I have a Vuex store which has a roster object. The roster object has an array of subteam objects. Each subteam object has an array of position objects. How do I count the total positions?

See the following getter:

totalPositions : function (state) {
    let reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
    return state.roster.subteams.reduce(reducer);
}

When I log the result, I get something like:

"[object Object]33010600000000000000000000000000000"

The digits in the string closely resemble the actual lengths of the position arrays, but not exactly. I tried using parseInt (even though array.length should be an integer):

let reducer = (accumulator, subteam) => {
    return accumulator + parseInt(subteam.positions.length,10);
};

It didn't help.

1 Answer 1

3

You must pass an initial value to the reduce function.

totalPositions : function (state) {
    const reducer = (accumulator, subteam) => accumulator + subteam.positions.length;
    return state.roster.subteams.reduce(reducer, 0);
}

If no initial value is supplied, the first element in the array will be used.

Since the subteam looks like an object, it is transformed into string [object Object] in the addition.

const obj = {};
console.log(obj + 13)
// => "[object Object]13"

Then say "[object Object]3" + 3 is "[object Object]33", etc. as the accumulator is now a string.


I really recommend you watch the Wat lightning talk by Gary Bernhardt from CodeMash 2012.

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

1 Comment

You are a legend Emile.

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.