3

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?

3 Answers 3

3

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;
})
Sign up to request clarification or add additional context in comments.

7 Comments

You beat me. The array of indices can be generated with stations.map((_,i) => i)
Or maybe Object.keys(stations).sort?
definately best solution for me :)
@Nickolay That would include non-integer keys (if any), to ignore them I recommend using only array methods. Array.from(stations.keys()) is a short polyfillable alternative.
@Nickolay: Nice idea (concise especially), but don't forget that will get you strings not integers.
|
1

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>');

Comments

0

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

2 Comments

Did you mean to clone the array into tempArray? Then you missed a .slice() call. Your current code does mutate the stations array, and each of the objects within.
@Bergi Thank you. I added it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.