Problems › JavaScript › data
The order that sorts
A report lists items by rank without disturbing the source rows: instead of the values, it wants their positions.
- Return the original positions (counting from zero) that would put the values in ascending order.
- When values are equal, their original-index order is kept.
sortedIndexOrder(values: list<int>) → list<int>
Where you start
function sortedIndexOrder(values) {
}
Worked examples
| Call | Result |
|---|---|
sortedIndexOrder([40,10,30,10]) | [1,3,2,0] |
sortedIndexOrder([20,10,30,10]) | [1,3,0,2] |
sortedIndexOrder([1,2,3]) | [0,1,2] |
sortedIndexOrder([3,2,1]) | [2,1,0] |
Hint
Sort a list of the indices with a comparator that looks the values up, falling back to the index itself on a tie.
Reference solution in JavaScript
function sortedIndexOrder(values) {
const idx = [];
for (let i = 0; i < values.length; i++) idx.push(i);
idx.sort((a, b) => values[a] - values[b] || a - b);
return idx;
}