# 数组排序

2021年09月15日 阅读数：1

1.纯数字数组数组

```// 纯数字数组排序
let arr = [3, 4, 5, 1, 2]
// 从小到大
console.log(arr.sort());
// 也是从小到大
console.log(arr.sort((a, b) => a - b));
// 从大到小
console.log(arr.sort((a, b) => b - a));```

2.数组对象属性排序spa

(1)对象的属性值是数字code

```let arr = [
{ name: 'zs', age: 12 },
{ name: 'ls', age: 6 },
{ name: 'ww', age: 24 },
];
// 对象的数字属性排序
// 从小到大
let compare = (property) => (a, b) => a[property] - b[property]
console.log(arr.sort(compare('age')));
// 从大到小
let compare2 = (property) => (a, b) => b[property] - a[property]
console.log(arr.sort(compare2('age')));```

（2）对象的属性值不是数字blog

①按英文字母a-z排序 或 z-a排序

``` let data = [
{ name: 'Bob', score: '95', age: '18' },
{ name: 'Amy', score: '86', age: '18' },
{ name: 'Coco', score: '36', age: '18' },
{ name: 'Mark', score: '80', age: '18' },
{ name: 'Frank', score: '40', age: '18' }
];
let newData = [...data]
let newData2 = [...data]
// a-z
let compare =  property=>(a,b)=> a[property].charCodeAt(0)- b[property].charCodeAt(0)
console.log(newData.sort(compare('name')));

// z- a
let compare2= property=>(a,b)=> b[property].charCodeAt(0)- a[property].charCodeAt(0)
console.log(newData2.sort(compare2('name')));```

②按拼音顺序排序 或 按拼音逆序排序console

```  let data = [
{name: '张三',age:12},
{name: '李四',age:23},
{name: '王五',age:23},
{name: '陈六',age:23},
]

let newData = [...data]
let newData2 = [...data]
// 拼音a-z
let compare = property=>(a,b)=> a[property].localeCompare(b[property],'zh')
// 拼音z-a
let compare2 = property=>(a,b)=> b[property].localeCompare(a[property],'zh')
console.log(newData.sort(compare('name')));
console.log(newData2.sort(compare2('name')));```