Ask Your Question
3

How can an array in Javascript be sorted and then represented by an array of indices that show the original positions of the sorted elements?

asked 2023-01-25 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-02-22 00:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-01-25 11:00:00 +0000

Seen: 9 times

Last updated: Feb 22 '22