Home > Software design >  calculate the pourcentage of the difference between two elements in array
calculate the pourcentage of the difference between two elements in array

Time:08-04

I want to render the percentage of the different data between two array elements (between two totals). How to do that?

//...
const [perc, setPerc] = useState(0);

const res = await userRequest.get("orders/income");
setPerc((res.data[1].total * 100) / res.data[0].total - 100);
console.log(res.data);

return(
  <div>{perc}%</div>
)

clg res.data shows:

0: {_id: 11, total: 20}
1: {_id: 12, total: 60}

The expected percentage from this data is 33%

The actual percentage is 60%

CodePudding user response:

I think you only need to remove the -100 at the end of your setPerc And if you want the % of the first element relative to the second you also need to swap to [0] and [1]

  • Related