In string is indented.
And when the sum is greater than 1000, it is impossible to get Total.
look at the picture please It will be more clear
const Total = () => {
const formValues = [
{sum: '10', expenseType: ''},
{sum: '1 000', expenseType: ''},
{sum: '1 000', expenseType: ''},
{sum: undefined, expenseType: ''},
]
const total = formValues.reduce((x, { sum }: { sum: number }) => Number(x) Number(sum), 0);
console.log(total)//NaN
};
CodePudding user response:
Accommodating for the case where sum
is undefined
in your reduce()
logic is pretty straightforward and can be done as follows:
const total = formValues.reduce((x, { sum }: { sum: number }) =>
Number(x) Number(sum || 0), 0);
However, that still leaves the problem of your number strings containing non-number characters. Borrowing the regex from this answer to clean up the string:
const Total = () => {
const formValues = [
{sum: '10', expenseType: ''},
{sum: '1 000', expenseType: ''},
{sum: '1 000', expenseType: ''},
{sum: undefined, expenseType: ''},
];
const total = formValues.reduce((x, { sum }) =>
Number(x) Number((sum || '').replace(/^(-)|[^0-9.,] /g, '$1')), 0);
console.log(total)//NaN
};
Total();
CodePudding user response:
Try it
const total = formValues.reduce((x, { sum }: {sum: string}) => Number(sum) ? Number(x) Number(sum) : Number(x), 0);