1

I have a large object that I need to sort by a value, so that is is listed in descending order (the range is 7-2). At the moment, I'm not sure what is really handling the sorting order, it seems fairly random to me though I assume there is some logic.

Here is an example subset of the data:

property_list = {
   1 : {
       description : '...',
       specs : {
          bedroom_number: 7
       }
   },
   2 : {
      description : '...',
      specs : {
         bedroom_number: 3
      }
   },
   3 : {
      description : '...',
      specs : {
          bedroom_number: 5
      }
   }
}

So I need to reorder by specs.bedroom_number so that they are arrange as 7, 5, 3 in terms of the bedroom number value.

Is this sort of sorting possible? Or does it require some sort of loop to work through the object and add each object to a new set of data?

user1486133
  • 1,309
  • 3
  • 19
  • 37
  • 1
    Objects don't have an order. You can sort the *keys* of an object in an array use that or you can store your data in an array instead of an object. – Mike Cluck Oct 20 '16 at 22:04
  • @MikeC So this is only possible with an array? How is the ordering done with an array? – user1486133 Oct 20 '16 at 22:14
  • 1
    If you have them in an array, you can use the [`sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) function. Pass it your own sorting function so you compare the `spec.bedroom_number` values. The link I posted shows an example of how to write your own sorting function. – Mike Cluck Oct 20 '16 at 22:16

1 Answers1

2

You can create a new array of objects out of your variable property_list and then sort by specs.bedroom_number with the use of Array.prototype.sort():

var property_list = {1: {description: '...',specs: {bedroom_number: 7}},2: {description: '...',specs: {bedroom_number: 3}},3: {description: '...',specs: {bedroom_number: 5}}},
    arr = Object
        .keys(property_list)
        .map(function (key) {
            return property_list[key];
        })
        .sort(function (a, b) {
            return b.specs.bedroom_number - a.specs.bedroom_number;
        });

console.log(arr);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46