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
CodePudding user response:
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 );
CodePudding user response:
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)