数组的排序

2019-08-22  本文已影响0人  尤雨溪的大迷弟

1.sort排序

sort方法排序结果是按照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]

所以我们添加一个排序函数:

  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]

以数组中的对象的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}
上一篇 下一篇

猜你喜欢

热点阅读