Home > Net >  How to sort an array of objects based on numbers?
How to sort an array of objects based on numbers?

Time:03-17

I have a Json file who contains the follow array of objects:

{
    "prospects": [
      {
        "name": "Evan Neal",
        "college": "Alabama",
        "positionAcronym": "OT",
        "grade": 8,
        "id": 1
      },
      {
        "name": "Kyle Hamilton",
        "college": "Notre Dame",
        "positionAcronym": "FS",
        "grade": 10,
        "id": 2
      },
      {
        "name": "Aidan Hutchinson",
        "college": "Michigan ",
        "positionAcronym": "Edge",
        "grade": 10,
        "id": 3
      },
      {
        "name": "Derek Stingley",
        "college": "LSU ",
        "positionAcronym": "CB",
        "grade": 6,
        "id": 4
      },
      {
        "name": "Brian Robinson Jr",
        "college": "Alabama",
        "positionAcronym": "RB",
        "grade": 4,
        "id": 5
      }
    ]
  }

Right now the order is the standard order of the objects on the array

// [ Evan Neal, Kyle Hamilton, Aidan Hutchinson, Derek Stingley, Brian Robinson Jr ]

But I wanna to sort these objects based on his "grade" value. The result has to be something like that. It is possible?

// [ Aidan Huthinson (grade is 10), Kyle Hamilton (grade is 10), Evan Neal (grade is 8), Derek Stingley (grade is 6), Brian Robinson Jr (grade is 4)]

I'm getting the data from a fetch method:

fetch('/data/prospectsData.json')
.then(res => res.json())
.then(data => {
    data.prospects.map(player => {

       // My code to create the list of elements

    })
})

CodePudding user response:

yourArray.sort((a, b) => a.grade - b.grade) will sort your array by the field grade

CodePudding user response:

  • since it's a object. this will sort grade high to low
data.prospects.sort((a, b) => b.grade - a.grade);
  • Related