-1

So basically I have an array with a lot of numbers. And I wanna sort into it, well sorting actually works but after I sort into it I wanna know in which place the sorted number was. This is my code:

console.log(leaderBoard1.sort((a,b)=>b-a));

Well it retuns all the values like: ['1', '2', '3'] and so on, but what I basically want is to get the position of it. By position mean if we want to get something from an array we do: array[0] right? I wanna get the position between the array[position] something like this.

Thanks

Min Siam
  • 13
  • 1
  • 5
  • Is [this](https://stackoverflow.com/questions/3730510/javascript-sort-array-and-return-an-array-of-indices-that-indicates-the-positio) what you want? – bui Oct 12 '22 at 00:59
  • 1
    It's not quite clear what you mean by ***... what I basically want is to get the position of it.*** Please show what what you have done so far and wha the expected result should look like. – PeterKA Oct 12 '22 at 01:15

2 Answers2

1

if you want to get the index before the data get sorted, you can turn it into an object that saves the index's value and then sort it.

  leaderBoard1 = [1,3,4,8,1]
    let sorted = leaderBoard1.map((val,index) => {return {data: val, index: index}}).sort((a,b)=>{ return b.data -a.data});
    
    console.log(sorted)
Feis
  • 51
  • 3
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply. – jasie Oct 12 '22 at 06:12
  • That helped! Also I'm sorry I'm new to stackoverflow. Please suggest me a title of the question... – Min Siam Oct 16 '22 at 12:02
0

You have to start by capturing the position of every item, {item, index}, then sort the list based on item prop as in the following demo:

const list = [5,0,2,3,8,9,5,6,8,4,1],

sorted = list
    //first capture the position of every element
    .map((item, index) => ({item, index}))
    //Now sort based on item
    .sort((a,b) => a.item - b.item);
    
console.log( sorted );
PeterKA
  • 24,158
  • 5
  • 26
  • 48