如何为“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
}
但它返回的数组未按姓氏/名称
排序答案 0 :(得分:0)
你实际上非常接近。
问题在于:
return this.users.sort(surname).sort(name);
您首先按surname
排序,然后排序name
忽略 surname
。
解决方案是使用同时处理属性的函数。因此,将这些排序函数合并为一个。
另一方面,您计算的是就地。您可能希望克隆数组,返回计算属性中的已排序副本。
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;