This is a Sort example : const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});
Array products
let a = [{
"_id": "61ce7052b2c78ab4ae89c731",
"title": "Alcohol",
"description": "Para medicina",
"categories": [
"Art"
],
"price": 300,
"rating": 1,
"image": "https://veterinariaeljockey.com.ar/wp-content/uploads/2020/12/alcohol-etilico-purocol-500cc.jpg",
"quantity": 3,
"createdAt": "2021-12-31T02:52:02.833Z",
"updatedAt": "2021-12-31T02:52:02.833Z",
"__v": 0
},
{
"_id": "61ce6fefb2c78ab4ae89c72e",
"title": "Liquido de Frenos",
"description": "Elemento para el auto",
"categories": [
"Services"
],
"price": 2500,
"rating": 1,
"image": "http://proyesa.com.sv/site/wp-content/uploads/2017/02/liquido-para-frenos-bosch.jpg",
"quantity": 23,
"createdAt": "2021-12-31T02:50:23.974Z",
"updatedAt": "2021-12-31T02:50:23.974Z",
"__v": 0
}
]
Sort
useEffect(() => {
if (time === "newest") {
if (!filterProducts || filterProducts.length == 0) {
setFilterProducts(...products);
} else {
setFilterProducts((prev) =>
[...prev].sort((a, b) => a.createdAt - b.createdAt)
);
}
} else {
setFilterProducts((prev) => [...prev].sort((a, b) => b.createdAt - a.createdAt));
}
}, [time]);
When I touch "Newest" products sort by default. But I touch "Oldest" nothing happens
Thanks for helping!
CodePudding user response:
createdAt is a string, in order to sort the list by date you must convert it into Date.
example:
setFilterProducts((prev) =>
[...prev].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));