[英]Changing the order of an array based on another with javascript sort
[英]Sort array in JavaScript based on name and order parameter
在我当前的项目中,我必须根据特定的排序参数对一组对象进行排序:
顺序(向上/向下),
和排序类型(名称、描述、类别)。
因此,我使用语法sort = [type, order]
创建了一个排序数组。
现在我想根据排序类型和顺序对我的对象数组进行排序。 我目前的实现是:
computed: {
accountsList() {
var list = this.$store.getters["accounts/accountsList"];
if (this.$route.query.fave) {
list = list.filter((x) => x.fave == true);
} else if (this.$route.query.my) {
//my
}
if (this.sort.length != 0) {
list = list.sort((a, b) => {
if (this.sort[1] == "up") {
if (a[this.sort[0]] < b[this.sort[0]]) {
return 1;
}
if (a[this.sort[0]] > b[this.sort[0]]) {
return -1;
}
return 0;
} else {
if (a[this.sort[0]] < b[this.sort[0]]) {
return -1;
}
if (a[this.sort[0]] > b[this.sort[0]]) {
return 1;
}
return 0;
}
});
}
return list;
},
我的排序数组更改如下:
changeSort(sort, order) {
if (this.sort[0] == sort && this.sort[1] == order) {
this.sort = [];
} else {
this.sort = [sort, order];
}
我的对象数组包括:
[{ category: "test2",
description: "adadad",
name: "adadadadad"
},
{
category: "test",
description: "my description",
name: "NewAccount"
},
{
category: "test",
description: "My other description",
name: "another new account"
}]
目前它不能正常工作,它只是对两个元素进行排序,而其他元素则保持不变。
你可以使用 Lodash 的 orderBy 函数作为下面的例子:
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
进一步参考: https : //lodash.com/docs/4.17.15#orderBy
我会简化您的代码并提出一个问题 - 您是否返回list
? 也许你可以提供一个完整的方法,甚至是完整的工作示例。
export {
data() {
list: []
},
methods: {
sortList() {
if (this.sort.length != 0) {
let col = this.sort[0] || 'id', // default col
dir = this.sort[1];
this.list = this.list.sort((a, b) => {
let colA = a[col],
colB = b[col];
if (dir == "up") {
return (colA < colB ? 1 : (colA > colB ? -1 : 0))
} else {
return (colA < colB ? -1 : (colA > colB ? 1 : 0))
}
});
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.