0

I have a very simple problem. I wanted to get the total gross using reduce function. My problem is that its a string but I already added + to make it a number. I wonder that output is still NaN?

const hello = [
    {
        "gross": "391.50",
    },
    {
        "gross": "489.80",
    }
]

const final = hello.reduce((prev, cur) => Number(prev.gross) + Number(cur.gross), 0);

console.log(final, 'FINAL')

0

1 Answer 1

0

prev is the running total, not an object, there's no prev.gross.

const hello = [{
    "gross": "391.50",
  },
  {
    "gross": "489.80",
  }
]

const final = hello.reduce((prev, cur) => prev + Number(cur.gross), 0);

console.log(final, 'FINAL')

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

2 Comments

is Number or + better?
The difference is negligible. Number is more readable IMHO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.