I have the following array of objects:
[{"id":0,"name":"Katy","age":22},
{"id":2,"name":"Lucy","age":12},
{"id":1,"name":"Jenna","age":45},
{"id":3,"name":"Ellie","age":34}]
I need to add another key into the objects (PaymentCategory) where whichever object has the lowest ID is added the key with value "Cash", the one with highest ID "Card", and everything in between "Cheque"; the array also must then be sorted by ID.
Hence required output would be:
[{"PaymentCategory":"Cash","id":0,"name":"Katy","age":22},
{"Payment Category":"Cheque","id":1,"name":"Jenna","age":45},
{"Payment Category":"Cheque","id":2,"name":"Lucy","age":12},
{"Payment Category":"Card","id":3,"name":"Ellie","age":34}]
How can we achieve this result in the most efficient way, i.e. fewest number of iterations, highest performance?
Here's what I tried:
const min = array.reduce((prev,curr)=> prev.id<curr.id?prev:curr)
const max = array.reduce((prev,curr)=> prev.id>curr.id?prev:curr)
min.PaymentCategory = "Cash"
max.PaymentCategory = "Credit"
const result =[min, max]
The problem with this is:
- I'm looping through it twice, one for
max, one formin. - How do I get the "middle" values?