字符窜数组排序
var strArray = ["abc", "cds", "sdc", "afd", "fff", "kk", "k12"];
strArray.sort();
console.log(strArray);
[ ‘abc’, ‘afd’, ‘cds’, ‘fff’, ‘k12’, ‘kk’, ‘sdc’ ]
var strArray = ["abc", "cds", "sdc", "afd", "fff", "kk", "k12"];
strArray.sort((a, b) => {
return b.localeCompare(a);
});
console.log(strArray);
[ ‘sdc’, ‘kk’, ‘k12’, ‘fff’, ‘cds’, ‘afd’, ‘abc’ ]
对象数组排序
var socores = [
{ name: 'zhangsan', socre: 40 },
{ name: 'lisi', socre: 70 },
{ name: 'wangwu', socre: 50 },
{ name: 'xiaoming', socre: 100 },
{ name: 'xiaohong', socre: 80 },
];
socores.sort();
console.log(socores);
[ { name: ‘zhangsan’, socre: 40 }, { name: ‘lisi’, socre: 70 }, { name: ‘wangwu’, socre: 50 }, { name: ‘xiaoming’, socre: 100 }, { name: ‘xiaohong’, socre: 80 } ]
对于对象数组来说,直接进行sort()排序好像并不起作用,这时候我们就要重写sort()内部的方法,例子如下:
var socores = [
{ name: 'zhangsan', socre: 40 },
{ name: 'lisi', socre: 70 },
{ name: 'wangwu', socre: 50 },
{ name: 'xiaoming', socre: 100 },
{ name: 'xiaohong', socre: 80 },
];
socores.sort((a, b) => {
return a.socre > b.socre ? 1 : -1;
});
console.log(socores);
[{ name: ‘zhangsan’, socre: 40 }, { name: ‘wangwu’, socre: 50 }, { name: ‘lisi’, socre: 70 }, { name: ‘xiaohong’, socre: 80 }, { name: ‘xiaoming’, socre: 100 } ]