簡體   English   中英

對“日”“周”“月”和“年”進行排序

[英]Sorting "day" "week" "month" and "year"

我有一組來自 API 的對象

[
{path: 'image', location: 'LOCATION_1', time: 'day'}
1: {path: 'image', location: 'LOCATION_2', time: 'week'}
2: {path: 'image', location: 'LOCATION_1', time: 'year'}
3: {path: 'image', location: 'LOCATION_1', time: 'week'}
4: {path: 'image', location: 'LOCATION_1', time: 'month'}
5: {path: 'image', location: 'LOCATION_2', time: 'day'}
6: {path: 'image', location: 'LOCATION_2', time: 'month'}
7: {path: 'image', location: 'LOCATION_2', time: 'year'}
]

我想根據時間對它們進行排序,但是當我這樣做時,它就像

day
month
week
year

有沒有辦法讓它像:

day
week
month
year

我在 javascript 中使用功能組件。

在排序 function 中,您正在與字符串進行比較,這就是您獲得按字母順序排序的列表的原因。 如果您想要自定義訂單,您可以創建 map 以遵循訂單。

 const data = [ {path: 'image', location: 'LOCATION_1', time: 'day'}, {path: 'image', location: 'LOCATION_2', time: 'week'}, {path: 'image', location: 'LOCATION_1', time: 'year'}, {path: 'image', location: 'LOCATION_1', time: 'week'}, {path: 'image', location: 'LOCATION_1', time: 'month'}, {path: 'image', location: 'LOCATION_2', time: 'day'}, {path: 'image', location: 'LOCATION_2', time: 'month'}, {path: 'image', location: 'LOCATION_2', time: 'year'}, ]; const timeMap = { day: 0, week: 1, month: 2, year: 3, } data.sort((a, b) => { return timeMap[a.time] < timeMap[b.time]? -1: 1; }); console.log(data);

使用這樣的排序方法
mdn: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

 let arr = [ {path: 'image', location: 'LOCATION_1', time: 'day'}, {path: 'image', location: 'LOCATION_2', time: 'week'}, {path: 'image', location: 'LOCATION_1', time: 'year'}, {path: 'image', location: 'LOCATION_1', time: 'week'}, {path: 'image', location: 'LOCATION_1', time: 'month'}, {path: 'image', location: 'LOCATION_2', time: 'day'}, {path: 'image', location: 'LOCATION_2', time: 'month'}, {path: 'image', location: 'LOCATION_2', time: 'year'} ]; let sortBy = ["day", "week", "month", "year"] console.log(arr.sort((a,b) => sortBy.indexOf(a.time) - sortBy.indexOf(b.time)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM