Home > Mobile >  How to sort array of object with a condition?
How to sort array of object with a condition?

Time:10-18

    let array = [
  {
    "vendorBidId": null,
    "participantName": "test [email protected]",
    "bidAmount": 0,
    "productionRate": null,
    "bidTime": null,
    "isYou": false,
    "awarded": false
  },
  {
    "vendorBidId": 16,
    "participantName": "test [email protected]",
    "bidAmount": 131,
    "productionRate": 131,
    "bidTime": "2021-09-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": 20,
    "participantName": "[email protected]",
    "bidAmount": 30,
    "productionRate": 30,
    "bidTime": "2021-0a-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": 30,
    "participantName": "[email protected]",
    "bidAmount": 40,
    "productionRate": 40,
    "bidTime": "2021-0a-18T08:11:21.295",
    "isYou": true,
    "awarded": false
  },
  {
    "vendorBidId": null,
    "participantName": "test [email protected]",
    "bidAmount": 0,
    "productionRate": null,
    "bidTime": null,
    "isYou": false,
    "awarded": false
  },
  {
    "vendorBidId": 40,
    "participantName": "[email protected]",
    "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

CodePudding user response:

  1. Separate your arrays based in vendorBidId being null or not.
  2. Sort the part you want to sort
  3. concat the other array.

CodePudding user response:

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 

CodePudding user response:

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);
  • Related