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}
CodePudding user response:
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.
CodePudding user response:
You can use Array.sort for that:
const data = [
{_id: 10, total: 990},
{_id: 11, total: 20},
{_id: 6, total: 448},
{_id: 9, total: 700},
{_id: 8, total: 100},
{_id: 7, total: 900}
]
const sorted = data.sort((a, b) => a._id - b._id)
console.log(data)
In this example I use subtraction "hack" do determinate order. It works only for numbers, if you want to compare strings, for example, you can pass custom compare function (compareFunction(a, b)
) that returns:
> 0
- sort a after b< 0
- sort a before b=== 0
- keep original order of a and b
CodePudding user response:
You can use the built-in sort
function like this:
myArray = [{_id: 10, total: 990},
{_id: 11, total: 20},
{_id: 6, total: 448},
{_id: 9, total: 700},
{_id: 8, total: 100},
{_id: 7, total: 900}];
// now myArray is sorted "in place" in a descending order.
myArray.sort((a, b) => a._id - b._id);
// you can flip it so it is ordered in an ascending order:
myArray.sort((a, b) => b._id - a._id);
Notice that sorting by id is not recommended because there is no business logic related to the order of ids. Why should item 1 be shown before item 2?
The order should depend on a business-related field, for example, modified date.
CodePudding user response:
If possible, you should sort the data directly from the API.
Otherwise, you can use the Array#sort function once you get the data
const arr = [{
_id: 10,
total: 990
}, {
_id: 11,
total: 20
}, {
_id: 6,
total: 448
}, {
_id: 9,
total: 700
}, {
_id: 8,
total: 100
}, {
_id: 7,
total: 900
}]
arr.sort((a, b) => a._id - b._id)
console.log(arr)