js sort 根据两个字段为条件排序

栗子
const arr = [
    {
        name: '一',
        outdate_days: 0,
        surplus_days: 1
    },
    {
        name: '二',
        outdate_days: 3,
        surplus_days: 0
    },
    {
        name: '三',
        outdate_days: 2,
        surplus_days: 0
    }
]
arr.sort((a, b) => {
  if (a.outdate_days <= 0) {
    if (b.outdate_days <= 0) {
      return a.surplus_days - b.surplus_days
    } else {
      return a.surplus_days - b.outdate_days
    }
  }
  if (a.surplus_days <= 0) {
    if (b.surplus_days <= 0) {
      return a.outdate_days - b.outdate_days
    } else {
      return a.outdate_days - b.surplus_days
    }
  }
})
//  结果
[
    {
        "name": "一",
        "outdate_days": 0,
        "surplus_days": 1
    },
    {
        "name": "三",
        "outdate_days": 2,
        "surplus_days": 0
    },
    {
        "name": "二",
        "outdate_days": 3,
        "surplus_days": 0
    }
]

你可能感兴趣的:(js sort 根据两个字段为条件排序)