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)
    }
}
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. Commented Feb 22, 2022 at 4:32
  • Does this answer your question? JS - Sorting array of objects Commented Feb 22, 2022 at 4:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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}) );

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.