0

I currently have an array object (not sure if this is the accurate name) that is comprised of nested key value pairs. I want to be able to sort this by the values within the nested objects.

For example:

var ObjArray = [
    { id = 1,
      info = {
          number = 4,
          name = "foo"
       }
    },
    { id = 4,
      info = {
          number = 12,
          name = "bar"
       }
    },
    { id = 9,
      info = {
          number = 2,
          name = "fizz"
       }
    }
];

So ideally I could sort this object based on the 'number' property, and the resulting array object would have sub objects ordered by the number value within the info.

I've found a similar question (Sorting an object of nested objects in javascript (maybe using lodash?)) but doesn't account for another level of nested objects.

dreamkiller
  • 189
  • 3
  • 17

1 Answers1

3

The sorting function needed is

ObjArray.sort((a,b) => a.info.number - b.info.number);

This will sort them ascending

For descending :

ObjArray.sort((a,b) => b.info.number - a.info.number);

var ObjArray = [{
    id: 1,
    info: {
      number: 4,
      name: "foo"
    }
  },
  {
    id: 4,
    info: {
      number: 12,
      name: "bar"
    }
  },
  {
    id: 9,
    info: {
      number: 2,
      name: "fizz"
    }
  }
];

ObjArray.sort((a,b) => a.info.number - b.info.number);

console.log(ObjArray);
Weedoze
  • 13,683
  • 1
  • 33
  • 63