0

I am trying to get an ordered array of index from another array in typescript.

Let me give examples: consider a function that receives an array of any size and returns another array with the ordered indexes of the Input:

  • ex1: Input=(5.3, 2.4, 4.5, 6.2) > Output=(1,2,0,3).
  • ex2: Input=(10, 11, 5, 34, 3, 7, 17) > Output=(4,2,5,0,1,6,3).

I can't use array.sort() as will change the original array.

I'm stuck, as I have very litle experience whit JS and TS (rusty Delphi programmer).

Thanks in advance for any thoughts.

3 Answers 3

1

Use slice() to make a copy you can sort without mutating original, then map() to create an array of each sorted element's index in the original array.

const data = [5.3, 2.4, 4.5, 6.2],
      data2 = [10, 11, 5, 34, 3, 7, 17];

const sortedIndex = (arr) => {
  return arr.slice().sort((a, b) => a - b).map(n => arr.indexOf(n))
}

console.log(JSON.stringify(sortedIndex(data)));
console.log(JSON.stringify(sortedIndex(data2)));

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you.
0

Can you just copy the array then sort the copy?

var array0 = [4,2,5,7,1.6];
var array1 = [];
for(var i=0;i<array0.length;i++){
  array1.push(array0[i]);
}
array1.sort();
//array0 = [4,2,5,6,1.6]
//array1 = [1.6,2,4,5,6]

4 Comments

This does not make a copy. Try running this yourself. The variables are both references to same array
Only if values are less than 10. Default for sort is to convert to string and 11 would come before 2
Thanks. i think in that case i would get the input array sorted, but not the indexes from the input array sorted into a new array! for this ex.of the array0 I would like to get: output = (4,1,0,2,3)! The array i am using is only numbers!
My bad, I thought they just wanted to use the .sort() method and not have it modify the original array, just misinterpreted the question
0

Only need two lines of code to do this:

var unsortedArray = [6, 4, 9, 1, 5];
var sortedArray = unsortedArray.slice().sort();

console.log(sortedArray);      // [1, 4, 5, 6, 9]
console.log(unsortedArray);    // [6, 4, 9, 1, 5]

Comments

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.