Home > Software engineering >  Tell users how to sort an array, but not sorting for them. [js]
Tell users how to sort an array, but not sorting for them. [js]

Time:08-26

Let's say I have an array [1, 10, 500, 25, 34].

Instead of using array.sort((a, b) => a - b) to make it look like [1, 10, 25, 34, 500], I want to tell the users how to sort it, like displaying [1, 2, 5, 3, 4].

I have searched many articles online, but they only show me how to display an correctly-sorted array for me but not telling users how to sort an array.

CodePudding user response:

  1. Map the array to [[0, 1], [1, 10], [2, 500], [3, 25], [4, 34]],
  2. sort it by the second element,
  3. iterate the sorted array and write the numbers 1-5 into a new array according to the position in the first array element.

const arr = [1, 10, 500, 25, 34];

const result = arr.map((el, idx) => ([idx, el]))
                  .sort(([,lhs], [,rhs]) => lhs - rhs)
                  .reduce((acc, [el], idx) => (acc[el] = idx   1, acc), []);
                  
console.log(result);

  • Related