My res.data always randomly sorted, how to sort res.data by _id ?
const [income, setIncome] = useState([]);
const [perc, setPerc] = useState(0);
useEffect(() => {
const getIncome = async () => {
try {
const res = await userRequest.get("orders/income");
setIncome(res.data);
setPerc((res.data[1].total * 100) / res.data[0].total - 100);
console.log(res.data);
} catch {}
};
getIncome();
}, []);
console.dev:
0: {_id: 10, total: 990}
1: {_id: 11, total: 20}
2: {_id: 6, total: 448}
3: {_id: 9, total: 700}
4: {_id: 8, total: 100}
5: {_id: 7, total: 900}
>Solution :
You can do this to sort based on it:
res.data.sort((x, y) => x._id - y._id)
This will sort in ascending order based on the _id attribute for each item of the res.data array.