Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to accomplish this is to create a new array of objects that hold the original value and the index it occupies in the original array. Sort this new array by the value attribute and then extract the index attribute into a new array.

Here is an example implementation:

const array = [5, 2, 8, 1, 9];
const indexedArray = array.map((value, index) => ({ value, index }));
// [{ value: 5, index: 0 }, { value: 2, index: 1 }, { value: 8, index: 2 }, { value: 1, index: 3 }, { value: 9, index: 4 }]
indexedArray.sort((a, b) => a.value - b.value);
// [{ value: 1, index: 3 }, { value: 2, index: 1 }, { value: 5, index: 0 }, { value: 8, index: 2 }, { value: 9, index: 4 }]
const indices = indexedArray.map(item => item.index);
// [3, 1, 0, 2, 4]

Note that this implementation assumes that the original array does not contain objects or values that have complex comparison rules. If that is the case, the sort function passed to sort() must be adapted to compare those values correctly.