Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an array of sorted indexes by value in object

I have mutlriple objects called stations. Each station has a property called money.

stations[0].money = 2000
stations[1].money = 500
stations[2].money = 1200
stations[3].money = 2200

I want to create an array of stations indexes (0,1,2 and 3 in this example) but sorted by ammount of money each station has ascending by money. So I want to have:

var moneyArray = [1, 2, 0, 3]

what is the most elegant way to do it?

like image 910
Kalreg Avatar asked Nov 25 '25 04:11

Kalreg


1 Answers

You can start with a normal array of indices (loop-generated, preferably) and sort that by the value of the object at the respective index in your stations array:

[0, 1, 2, 3].sort(function(ai, bi) {
    return stations[ai].money - stations[bi].money;
})
like image 125
Bergi Avatar answered Nov 27 '25 17:11

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!