0

So I'm having trouble sorting an array. I'm trying to make it descend from the highest average to the lowest. This is the table ->

[
    {
        "average": "86.8",
        "user": "User1"
    },
    {
        "average": "93",
        "user": "User2"
    },
    {
        "average": "91.5",
        "user": "User3"
    }
]

This is how I set the array

let usr = []
if (users.docs.length > 0) {
    for (const user of users.docs) {
        let exportable = user.data()
        usr.push(exportable)
    }
}
Elliot
  • 17
  • 2
  • The code segmet that you are posted only demonstrates how you have generated this array. This doesnot provide any information on how you performed sorting on the list. There are thousands of example availabe in this platform itself regarding sorting an array. Please refer them. – Nitheesh Feb 22 '22 at 04:32
  • Does this answer your question? [JS - Sorting array of objects](https://stackoverflow.com/questions/66852210/js-sorting-array-of-objects) – A1exandr Belan Feb 22 '22 at 04:48

2 Answers2

1

try this.

https://stackblitz.com/edit/js-vb6yxa

const data = [
  {
    average: '86.8',
    user: 'User1',
  },
  {
    average: '93',
    user: 'User2',
  },
  {
    average: '91.5',
    user: 'User3',
  },
];

const sortedData = data.sort((a, b) => b.average - a.average);
console.log(sortedData);

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

The reason why this works per MDN "If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.". When you provide a compare function to the sort() method, it instead sorts by number. a - b sorts in ascending order, while b - a does the opposite.

Here a link to a comment that explains this behavior more clearly: https://forum.freecodecamp.org/t/arr-sort-a-b-a-b-explanation/167677/3

k22pr
  • 189
  • 1
  • 9
0

use this.

const data = [
    {
        average : "86",
        user : 'user1',
    },
    {
        average : "93",
        user : 'user2',
    },
    {
        average : "91",
        user : 'user3',
    },
];
console.log(data.sort(function(a,b){return b.average - a.average}) );
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
Ipal
  • 135
  • 1
  • 10
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '22 at 06:57