简体   繁体   中英

Sort array in JavaScript based on name and order parameter

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.

You can use Lodash's orderBy function as the example below:

var users = [
  { 'user': 'fred',   'age': 48 },
  { 'user': 'barney', 'age': 36 },
  { 'user': 'fred',   'age': 40 },
  { 'user': 'barney', 'age': 34 }
];
 
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);

For further reference: https://lodash.com/docs/4.17.15#orderBy

I would simplify Your code and ask a question - do You return list ? Maybe You could supply a whole method, or even fully working example.

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))
           }
        });
     }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM