为两个属性Vuejs排序数组

时间:2018-04-11 14:44:34

标签: sorting vue.js

如何为“surname” - “name”等两个属性对Array对象进行排序?

我尝试连接但它不起作用,因为它仅排序第二次排序:

computed:{
   sortedArray: function() {
      function name(a, b) {
         if (a.name < b.name) return -1;
         if (a.name > b.name) return 1;

         return 0;
      }
      function surname(a, b) {
         if (a.surname < b.surname) return -1;
         if (a.surname > b.surname) return 1;
         return 0;
      }

      return this.users.sort(surname).sort(name);
   }
}

我也尝试过:

function surname(a, b) {
   return a.surname < b.surname || a.name < b.name
}

但它返回的数组未按姓氏/名称

排序

1 个答案:

答案 0 :(得分:0)

你实际上非常接近。

问题在于:

return this.users.sort(surname).sort(name);

您首先按surname排序,然后排序name 忽略 surname

解决方案是使用同时处理属性的函数。因此,将这些排序函数合并为一个。

另一方面,您计算的是就地。您可能希望克隆数组,返回计算属性中的已排序副本

&#13;
&#13;
new Vue({
  el: '#app',
  data: {
    users: [
      {name: "John", surname: "Nash"},
      {name: "Paul", surname: "Pringles"},
      {name: "Bob", surname: "Pringles"},
      {name: "Bob", surname: "Abbey"},
      {name: "Alice", surname: "Abbey"},
    ]
  },
  computed:{
     sortedArray: function() {
        function surnameName(a, b) {
           if (a.surname < b.surname) return -1;
           if (a.surname > b.surname) return 1;
           if (a.name < b.name) return -1;
           if (a.name > b.name) return 1;
           return 0;
        }
        // return this.users.sort(surnameName); // sorts in-place
        return [...this.users].sort(surnameName); // shallow clone + sort
     }
  }
})
&#13;
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>unsorted:<br>{{ users }}</p>
  <p>sorted:<br>{{ sortedArray }}</p>
</div>
&#13;
&#13;
&#13;