Home > Blockchain >  Array,Reduce() function initiates before data is passed into it - results in NaN
Array,Reduce() function initiates before data is passed into it - results in NaN

Time:11-08

I'm trying to perform a simple addition based on user inputs ( for dimensions of a box in cubic meters.. i want to sum up all the boxes they want to add ).

  const totalW = []
  const cubitMeters = (parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) / 1000000
  totalW.push(cubitMeters)

then in JSX I'm reducing it

  <Text>
    {totalW?.reduce((a, b) => a   b, 0).toFixed(2)}
  </Text>

Everything is fine, however as you can see the calculation for cubitMeters is a multiplication.. and unless all numbers are provided, it returns NaN. And it only works properly when the user finally enters all numbers, which isn't ideal.

How can I make sure that the function only is triggered when all numbers are entered?

CodePudding user response:

Try adding in an if statement

if (totalW.length === 0) {
  return
} else {
  ///return your totalW value
}

Otherwise, build an async function to do the calculation and await the result. This may work

const calculationFunction = async (err, response) => {
  let totalW = [];
  let calculation =
    (parseInt(height) * parseInt(width) * parseInt(length) * parseInt(count)) /
    1000000;
  if (calculation.length !== 0) {
    let cubitMeters = calculation;
    totalW.push(cubitMeters);
  } else {
    console.log("Not ready yet...");
  }
};

const answer = await calculationFunction();

Then do this:

if (answer.length > 0) {
  <Text>{answer?.reduce((a, b) => a   b, 0).toFixed(2)}</Text>;
} else {
  console.log("Still calculating...");
}

CodePudding user response:

Could you provide a complete use case? Based on the provided information it's a little bit hard to fully understand how to help. In a scenario where you use useState to store a input or more than one input you could simply validate it with onChange event on a input field. In the case you have two or more states you could use it to trigger the function after the last number is inserted.

Ex:

  1. User inserts first number on input, inserts space or comma and then inserts another number: you could split on the separator character and then use the result of te split to continue the operation.
  2. User provides first input; user provides second input; you trigger the function after the second value is inserted and validated.

CodePudding user response:

Ok guys! Thank you so much for taking the time to help me out. I really appreciate it. After talking with you, some things started to ring the bell and I finally came up with a solution.

    {totalW
       .filter((nan) => nan)
       .reduce((a, b) => a   b, 0)
       .toFixed(2)}

This function basically filters out all falsy values ( and apparently NaN is a falsy value ).. once I got it figured out, it was a piece of cake

  • Related