RJP RJP - 13 days ago 5
Javascript Question

Sorting object properties based on value

I have an array of objects:

[
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Caters":"10",
"Takes Reservations":"11",
"Smoking":"0",
"Dogs Allowed":"1",
"Outdoor Seating":"12",
"Coat Check":"0",
"Waiter Service":"14",
"Wi-Fi":"10",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
}
]


I want to sort this based on the value. So my result should be something like:

[
{
"Accept Credit Cards":"17",
"Take-Out":"17",
"Alcohol":"16",
"Good For Groups":"16",
"Wheelchair Accessible":"13"
AND SO ON.....

}
]


How will I do this? I tried a sort. But that just sorts based on the key. Any pointers appreciated.

Answer

As RyanZim has mentioned in the comments, there isn't really a purpose to sorting the properties of an object. JavaScript does not guarantee the property order, so you shouldn't rely on them being in order. You could, however, make an array of the properties and sort them based on the value in your object.

const arr = [  
   {  
      "Accept Credit Cards":"17",
      "Take-Out":"17",
      "Alcohol":"16",
      "Caters":"10",
      "Takes Reservations":"11",
      "Smoking":"0",
      "Dogs Allowed":"1",
      "Outdoor Seating":"12",
      "Coat Check":"0",
      "Waiter Service":"14",
      "Wi-Fi":"10",
      "Good For Groups":"16",
      "Wheelchair Accessible":"13"
   }
];

const sorted = Object.keys(arr[0]).sort((a, b) => arr[0][b] - arr[0][a]);

sorted.forEach(x => console.log(x + ': ' + arr[0][x]));

If you want to get even fancier and sort by the value then alphabetically:

const arr = [  
   {  
      "Accept Credit Cards":"17",
      "Take-Out":"17",
      "Alcohol":"16",
      "Caters":"10",
      "Takes Reservations":"11",
      "Smoking":"0",
      "Dogs Allowed":"1",
      "Outdoor Seating":"12",
      "Coat Check":"0",
      "Waiter Service":"14",
      "Wi-Fi":"10",
      "Good For Groups":"16",
      "Wheelchair Accessible":"13"
   }
];

const sorted = Object.keys(arr[0]).sort((a, b) => {
  if (arr[0][a] > arr[0][b]) return -1;
  if (arr[0][a] < arr[0][b]) return 1;
  if (a > b) return 1;
  if (a < b) return -1;
  return 0;
});

sorted.forEach(x => console.log(x + ': ' + arr[0][x]));