Home > Enterprise >  How to sort an array by a number inside w/ javascript
How to sort an array by a number inside w/ javascript

Time:02-22

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

CodePudding user response:

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

CodePudding user response:

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

  • Related