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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-01-25 11:00:00 +0000
Seen: 9 times
Last updated: Feb 22 '22
What is the usage of JavaScript in IntelliJ IDEA Community Edition?
What is the issue with using java Gson().fromJson to assign BigDecimal values?
How can a custom loop function shape be altered to resemble Swift more accurately?
How can Django Admin accommodate a variety of formats and locales for its input fields?
How can an array be passed using typo3 flexform xml and itemsProcConfig?