- 按照指定顺序排序
created () {
this.test()
},
methods: {
test () {
const arr = ['a', 'b', '秋', '夏', '冬', '春', 'c']
arr.sort(function (a, b) {
var order = ['冬', '秋', '夏', '春'] // order是规则
return order.indexOf(b) - order.indexOf(a)
})
console.log(arr) // ["春", "夏", "秋", "冬", "a", "b", "c"]
const obj = [
{ name: 'a' },
{ name: 'b' },
{ name: '秋' },
{ name: '夏' },
{ name: '冬' },
{ name: '春' },
{ name: 'c' }
]
obj.sort(function (a, b) {
var order = ['冬', '秋', '夏', '春'] // order是规则
return order.indexOf(b.name) - order.indexOf(a.name)
})
console.log(obj)
}
}
- 数组对象,按照指定字段排序
created () {
this.test()
},
methods: {
test () {
const arr = [
{ id: 3, name: '秋', date: '2021-07-01' },
{ id: 1, name: '春', date: '2021-01-01' },
{ id: 4, name: '冬', date: '2021-10-01' },
{ id: 2, name: '夏', date: '2021-04-01' }
]
const arr1 = arr.sort(this.sortByDate('date', 'ascend'))
// const arr2 = arr.sort(this.sortByDate('date', 'descend'))
console.log(arr1)
// console.log(arr2) // 不要同时console.log,排序会改变原数组顺序
},
// 数组对象 按日期字段(某一字段)排序 field:排序字段 order: 排序方式
sortByDate (field, order) {
return (x, y) => {
if (order === 'ascend') {
return Date.parse(x[field]) - Date.parse(y[field])
} else {
return Date.parse(y[field]) - Date.parse(x[field])
}
}
}
}