[英]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.