0

i want to sort my javascript array. I get the data from firebase db and store them in my array in the following manner. The users can rate the car from 1 to 5 (5 is the best).

pool[0].car_type (e.g. city car)
pool[0].car_name (e.g. Citroen C1)
pool[0].car_seats (e.g. 5)
pool[0].car_rating (e.g. 4)

pool[1].car_type 
pool[1].car_name
pool[1].car_size
pool[1].car_rating (e.g. 3)

pool[2].car_type
pool[2].car_name
pool[2].car_size
pool[2].car_rating (e.g. 5)

pool[n].car_type
pool[n].car_name
pool[n].car_size
pool[n].car_rating (e.g. 1)

After I stored the data in my array "pool". I would like to sort the pool array on the basis of the rating. This means that in my example. the array nbr. 2 (pool[2]) with the highest rating (5) should be first, after the pool[0] with a rating of 4 etc.

I tried with sort but since the array is "sorted" already (pool[0] - pool[n]) i couldn't find any solution.

Do you know any solution how I can sort my array that the index with the highest rate comes first?

Thanks, Chris

Chris
  • 415
  • 5
  • 19
  • What do you mean "the array is sorted already"? The `sort()` function re-orders them based on the comparison function you provide. Show what you tried. – Barmar Aug 02 '21 at 18:54
  • 1
    `pool.sort((a, b) => b.car_rating - a.car_rating)` – Barmar Aug 02 '21 at 18:55
  • Thanks Barmar! I will try that later!! I mean that the Index is already sorted and the blaues behind (dot noration) are unsorted. Im pretty Sure it is a simple solution but i just can't find it. – Chris Aug 02 '21 at 19:01
  • `sort()` changes the indexes. – Barmar Aug 02 '21 at 19:02
  • Ah ok. Ah Sure it has to... thanks you have me the push i needed! I Think i need to make a break. Thanks! – Chris Aug 02 '21 at 19:05

0 Answers0