简体   繁体   中英

How to sort array of object with a condition?

    let array = [
  {
    "vendorBidId": null,
    "participantName": "test+10@mail.com",
    "bidAmount": 0,
    "productionRate": null,
    "bidTime": null,
    "isYou": false,
    "awarded": false
  },
  {
    "vendorBidId": 16,
    "participantName": "test+2@mail.com",
    "bidAmount": 131,
    "productionRate": 131,
    "bidTime": "2021-09-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": 20,
    "participantName": "test@mail.com",
    "bidAmount": 30,
    "productionRate": 30,
    "bidTime": "2021-0a-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": 30,
    "participantName": "test@mail.com",
    "bidAmount": 40,
    "productionRate": 40,
    "bidTime": "2021-0a-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": null,
    "participantName": "test+10@mail.com",
    "bidAmount": 0,
    "productionRate": null,
    "bidTime": null,
    "isYou": false,
    "awarded": false
  },
  {
    "vendorBidId": 40,
    "participantName": "test@mail.com",
    "bidAmount": 50,
    "productionRate": 50,
    "bidTime": "2021-0a-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  }
]

I want to sort this array in ascending order(bidAmount), and if the vendorBidId is null don't sort keep in the bottom.

I tried like this

array.sort((a,b) => parseFloat(a.bidAmount) - parseFloat(b.bidAmount)).map((ele) => console.log(ele.bidAmount))

I'm need an out like 30,40,50,131,0,0, but for the my above code it will just sort only. I tried with reduce but that does't work properly

array.sort((a,b) => {
  const n = a.vendorBidId === null ? Number.MAX_VALUE : a.bidAmount;
  const m = b.vendorBidId === null ? Number.MAX_VALUE : b.bidAmount;
  return n - m; 
});
// "2.5" + "3.5" = "2.53.5"
// "2.5" - "3.5" = -1 
  1. Separate your arrays based in vendorBidId being null or not.
  2. Sort the part you want to sort
  3. concat the other array.

Building on what DragatS has shared.. just map through the result of the sort() like this to get the result of [30,40,50,131,0,0]

const res = array
.sort((a, b) => {
    const n = a.vendorBidId === null ? Number.MAX_VALUE : a.bidAmount;
    const m = b.vendorBidId === null ? Number.MAX_VALUE : b.bidAmount;
    return n - m;
})
.map(item => item.bidAmount);
console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM