JS排序问题(凑满减)

const list =[
  {title:'苹果',price:1},
  {title:'香蕉',price:4},
  {title:'鸭梨',price:3},
  {title:'西瓜',price:5},
  {title:'山竹',price:2}];

我想排序, 按照price大于3的正序, 然后再把小于3的倒序, 排在大于的数据后面, 求最优算法.

期望如下:

const list =[
 {title:'香蕉',price:4},
 {title:'西瓜',price:5},
 {title:'鸭梨',price:3},
 {title:'山竹',price:2},
 {title:'苹果',price:1}];
阅读 1.8k
1 个回答
list.sort((a, b) => {
    if(a.price > 3 && b.price > 3){
        return a.price - b.price
    }
    return b.price - a.price
})
推荐问题
宣传栏