这个问题与指出的问题不同,因为我想按字符串排序,然后是数字和字符串等。
我一直在离开
javascript sort array by multiple (number) fields
我的数据有以下内容:
function GetStudentList(){
var sl = [
{
"ClassOrder": 1,
"LastName": "Blow",
"FirstName": "Joe",
"Class": "170-2"
},
{
"ClassOrder": 2,
"LastName": "Jane",
"FirstName": "Sally",
"Class": "170-1"
},
{
"ClassOrder": 1,
"LastName": "Belmont",
"FirstName": "John",
"Class": "170-1"
}
]
return(sl);
}
然后我调用代码:
var selectedStudents = GetStudentList();
selectedStudents.sort(function(a,b){
return a.LastName - b,LastName;
};
当我在浏览器中跟踪它时似乎工作,但是一旦我离开sort函数,selectedStudents数组就会恢复。它确实有效,但只能使用ClassOrder数据。然后,如果我尝试按ClassOrder排序,然后按LastName排序,则无法再次运行。
return a.ClassOrder - b.ClassOrder || a.LastName - b.LastName
答案 0 :(得分:-1)
您不应将字符串与-
进行比较。相反,请分别使用<
或>
对降序或升序进行排序。
let sl = [
{
"ClassOrder": 1,
"LastName": "Blow",
"FirstName": "Joe",
"Class": "170-2"
},
{
"ClassOrder": 2,
"LastName": "Jane",
"FirstName": "Sally",
"Class": "170-1"
},
{
"ClassOrder": 1,
"LastName": "Belmont",
"FirstName": "John",
"Class": "170-1"
}
];
sl.sort((a, b) => {
if (a.LastName > b.LastName) return 1;
else if (a.LastName < b.LastName) return -1;
return 0;
});
console.log(sl);