1.sort排序
sort方法排序結(jié)果是按照ASCII排序:
var arr1 = [10,5,40,25,1000,1]
function fn1 (a,b) {
return a - b
}
function fn2 (a,b) {
return b - a
}
console.log(arr1.sort()) // [1, 10, 1000, 25, 40, 5]
所以我們添加一個排序函數(shù):
var arr1 = [10,5,40,25,1000,1]
function fn1 (a,b) {
return a - b
}
function fn2 (a,b) {
return b - a
}
console.log(arr1.sort(fn1)) // 升序 [1, 5, 10, 25, 40, 1000]
console.log(arr1.sort(fn2)) // 降序 [1000, 40, 25, 10, 5, 1]
以數(shù)組中的對象的key值排序:
var arr2 = [
{ price: 20, num: 50},
{ price: 50, num: 20},
{ price: 100, num: 10},
{ price: 10, num: 5},
{ price: 5, num: 500},
]
function fn3 (a,b) {
return a.price - b.price // 這里“ .” + key值
}
console.log(arr2.sort(fn3)) // 以價格排序
// (5) [{…}, {…}, {…}, {…}, {…}]
// 0: {price: 5, num: 500}
// 1: {price: 10, num: 5}
// 2: {price: 20, num: 50}
// 3: {price: 50, num: 20}
// 4: {price: 100, num: 10}