Home > Enterprise >  Calculate the difference between last two elements in array of objects
Calculate the difference between last two elements in array of objects

Time:08-04

I need to calculate the difference income total between last two months (_id).

{income[1]?.total} always get me a fixed number: 900.

How to calculate the total difference between last two elements?

Note: res.data already sorted by _id.

const [income, setIncome] = useState([]);
  const [perc, setPerc] = useState(0);
  useEffect(() => {
    const getIncome = async () => {
      try {
        const res = await userRequest.get("orders/income");
        const sort = res.data.sort((x, y) => x._id - y._id)
        setIncome(sort);
        setPerc((res.data[1].total * 100) / res.data[0].total - 100);
        console.log(sort);
      } catch {}
    };
    getIncome();
  }, []);

return(
  <div>{income[1]?.total} $</div>
)

this is my console.dev:

0: {_id: 6, total: 448}
1: {_id: 7, total: 900}
2: {_id: 8, total: 100}
3: {_id: 9, total: 700}
4: {_id: 10, total: 990}
5: {_id: 11, total: 20}
6: {_id: 12, total: 20}

CodePudding user response:

const [difference, setDifference] = useState(0); 

//... then later...

if(sort.length > 1){
    setDifference(sort[sort.length - 1].total - sort[sort.length - 2].total);
}

//...then in your JSX...

<div>{difference}</div>

This will give you the difference between the last two elements' total props in the sort array.

CodePudding user response:

if i get your problem right
you must get 2 last object of your array to do so you can write:

// last object of array
const arrayLen = sort.length - 1;

then you can get the second last one as well and then compare the two values.

import "./styles.css";
import React from "react";

export default function App() {
  const [income, setIncome] = React.useState([]);
  const [diff, setDiff] = React.useState(0);
  React.useEffect(() => {
    const getIncome = async () => {
      try {
        const res = [
          { _id: 6, total: 448 },
          { _id: 7, total: 900 },
          { _id: 8, total: 100 },
          { _id: 9, total: 700 },
          { _id: 10, total: 990 },
          { _id: 11, total: 20 },
          { _id: 12, total: 20 }
        ];
        const sort = res.sort((x, y) => x._id - y._id);
        setIncome(sort);
        const arrayLen = sort.length - 1;
        setDiff(Math.abs(sort[arrayLen].total - sort[arrayLen - 1].total));
      } catch {}
    };
    getIncome();
  }, []);

  return <div>{diff} $</div>;
}

Math.abs is used to change the negative number to positive.

I hope I could help.

  • Related