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.

3
  • Can you give an example with the desired output? Commented Aug 30, 2017 at 13:19
  • 1
    @destoryer — They want to sort ObjArray based on each_member.info.number. They don't want to sort info. Commented Aug 30, 2017 at 13:21
  • @Surely as Quentin said, that question discusses a similar case to the question link I posted. Thanks though. Commented Aug 30, 2017 at 13:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.