這是一個排序示例: const points = [40, 100, 1, 5, 25, 10]; 點排序(函式(a,b){return b - a});
陣列產品
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
}
]
種類
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]);
當我觸摸“最新”產品時,默認排序。但我觸摸“最舊”沒有任何反應
感謝您的幫助!
uj5u.com熱心網友回復:
createdAt 是一個字串,為了按日期對串列進行排序,您必須將其轉換為日期。
例子:
setFilterProducts((prev) =>
[...prev].sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/399358.html
標籤:javascript 节点.js 反应 MongoDB 表达
