JS排序问题(凑满减)

铁皮饭盒
  • 4.9k
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}];
回复
阅读 776
1 个回答
✓ 已被采纳
list.sort((a, b) => {
    if(a.price > 3 && b.price > 3){
        return a.price - b.price
    }
    return b.price - a.price
})
宣传栏