Reputation: 1012
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?
Upvotes: 3
Views: 78
Reputation: 664767
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;
})
Upvotes: 3
Reputation: 18997
By using a Temp variable you can do it this way. Else if you can afford to modify the main data then the temp variable can be eliminated.
var stations = [{money :2000},{money :500},{money :1200},{money :2200}]
var tempArray = stations.slice();
tempArray.forEach(function (value, i) {
value.index = i;
});
tempArray.sort(function(a, b){return a.money-b.money});
var finalResult = tempArray.map(function(a) {return a.index;});
document.write(JSON.stringify(finalResult));
Upvotes: 0
Reputation: 386660
You may have a look here: Sorting with map
// the array to be sorted
var stations = [
{ money: 2000 },
{ money: 500 },
{ money: 1200 },
{ money: 2200 },
];
// temporary array holds objects with position and sort-value
var mapped = stations.map(function (el, i) {
return { index: i, value: el.money };
})
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return a.value - b.value;
});
// container for the resulting order
var result = mapped.map(function (el) {
return stations[el.index];
});
// get the wanted keys
var keys = mapped.map(function (el) {
return el.index;
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(keys, 0, 4) + '</pre>');
Upvotes: 1