2017-08-24 18:26:57 0 评论 JavaScript Boy.Lee

Javascript 数组元素排序示例Demo

let orgArr: [{t: 'Google', c: 4}, {t: 'Facebook', c: 11}, {t: 'Twitter', c: 1}, {t: 'Yiilib', c: 2}]


// type = 1 降序, type = 2 升序
var compare = function (prop, type) {
  return function (obj1, obj2) {
    var val1 = obj1[prop]
    var val2 = obj2[prop]
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1)
      val2 = Number(val2)
    }

    if(type === 1){
      if (val1 < val2) {
        return 1
      } else if (val1 > val2) {
        return -1
      } else {
        return 0
      }
    }else{
      if (val1 < val2) {
        return -1
      } else if (val1 > val2) {
        return 1
      } else {
        return 0
      }
    }
  }
}

// 以属性'c' 进行降序排序
orgArr.sort(compareDesc('c'), 1) 
console.log(orgArr) //Facebook, Google, Yiilib, Twitter

// 以属性'c' 进行升序排序
orgArr.sort(compareAsc('c'), 2)
console.log(orgArr) //Twitter, Yiilib, Google, Facebook