In my current project I have to sort an array of objects based on specific sort parameters:
the order (up / down),
and the sort type(name, description, category).
Therefore I created a sort array with syntax sort = [type, order].
Now I want to sort my array of objects based on the sort type and order. My current implementation is:
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;
},
My sort array is changed like this:
changeSort(sort, order) {
if (this.sort[0] == sort && this.sort[1] == order) {
this.sort = [];
} else {
this.sort = [sort, order];
}
My array of objects consists of:
[{ category: "test2",
description: "adadad",
name: "adadadadad"
},
{
category: "test",
description: "my description",
name: "NewAccount"
},
{
category: "test",
description: "My other description",
name: "another new account"
}]
At the moment it's not working properly, it's just sorting two elements and leaves the other ones untouched.
this.sortand I think they meantlist.)