1

This is the numbers array which is defined in a React Redux reducer file:

const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};

In a component, I want to sum all the numeric values in all the objects in the numbers array only if inCart === true.

This is how I'm doing it:

useEffect(() => {
    const total = props.numbers.reduce((prev, current) => {
        if (current.inCart) return prev + current.num;
    }, 0);
    console.log(total);
}, []);

And this is the console log I get:

NaN

So it's not working, what am I doing wrong?

1
  • add an else...? Commented May 28, 2020 at 12:41

5 Answers 5

1

You need to return the updated prev at the end inside the reduce() method like:

const total = props.numbers.reduce((prev, current) => {
  if (current.inCart) prev += current.num;
  return prev;
}, 0);

const numbers = [
    { name: 'max', num: 3, inCart: false },
    { name: 'jack', num: 2, inCart: true },
    { name: 'jack', num: 2, inCart: true }
]

const total = numbers.reduce((prev, current) => {
  if (current.inCart) prev += current.num;
  return prev;
}, 0);

console.log(total);

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

Comments

0

Does this help?

const total = props.numbers.reduce((prev, current) => {
    return (current.inCart) ? prev + current.num : prev;
}, 0);

Comments

0

You forgot to return prev when current.inCart is false.

const total = props.numbers.reduce((prev, current) => {
            if (current.inCart) return prev + current.num;
            return prev;  
        }, 0);

It should be like this.

Comments

0

Reduce

props.numbers.reduce((acc, cur) => cur.inCart ? acc + cur.num : acc, 0);

or filter and reduce

const props = {
numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
}
console.log(
  props.numbers
    .filter(item => item.inCart)
    .reduce((acc, cur) => acc + cur.num, 0)
)

Comments

0

You could filter out the unnecessary items, and then reduce over the items inCart and accumulatively add up num property from each object.

const initialState = {
    numbers: [
        { name: 'max', num: 3, inCart: false },
        { name: 'jack', num: 2, inCart: true },
        { name: 'jack', num: 2, inCart: true }
    ]
};

initialState.numbers
  .filter(({ inCart }) => inCart)
  .reduce((acc, { num }) => acc += num, 0);

Comments

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.