'how reduce total sum , if at first I have a value of undefined

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

enter image description here

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
  };


Solution 1:[1]

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();

Solution 2:[2]

Try it

const total = formValues.reduce((x, { sum }: {sum: string}) => Number(sum) ? Number(x) + Number(sum) : Number(x), 0);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Петров Кирилл