0

If I have a JavaScript object like this:

list = {
    John: {
        DOB: '2017-02-01'
    },
    Rob: {
        DOB: '2016-07-09'
    },
}

How do I go about sorting this object into a list of objects sorted by their DOB. I have lodash installed, so using that is an option.

I would like the result to be something mappable, ie an array such as:

sorted_keys = ['Rob','John']

or

sorted_array = [
    {
        Rob: {
            DOB: '2016-07-09'   
        }
    },
    {
        John: {
            DOB: '2017-02-01'   
        }
    },
]
JayBee
  • 540
  • 1
  • 5
  • 22

2 Answers2

5

var list = {
    John: {
        DOB: '2017-02-01'
    },
    Rob: {
        DOB: '2016-07-09'
    }
}

var sortedKeys = Object.keys(list).sort(function(a, b) {
  return new Date(list[a].DOB) - new Date(list[b].DOB)
})

console.log(sortedKeys)

Or using arrow functions:

let list = {
    John: {
        DOB: '2017-02-01'
    },
    Rob: {
        DOB: '2016-07-09'
    }
}

let sortedKeys = Object.keys(list).sort((a, b) => new Date(list[a].DOB) - new Date(list[b].DOB))

console.log(sortedKeys)

Answering on your comment if there were strings:

let list = {
    John: {
        DOB: 'bbb'
    },
    Rob: {
        DOB: 'aaa'
    }
}

let sortedKeys = Object.keys(list).sort((a, b) => {
    if(list[a].DOB < list[b].DOB) return -1;
    if(list[a].DOB > list[b].DOB) return 1;
    return 0;
})

console.log(sortedKeys)
Mikhail Katrin
  • 2,304
  • 1
  • 9
  • 17
1

First of all, note that it's a bit strange that you have an object called list that's not a list, but an object.

It's possible to sort the key-value pairs in this object by following these steps:

  • Extract the keys, using Object.keys
  • Sort the keys by the alphabetic ordering of list[key].DOB values. Luckily, you can use localeCompare to compare dates in YYYY-MM-DD format.
  • Map the sorted keys to object of the desired final structure

Like this:

let sorted = Object.keys(list)
  .sort((a, b) => list[a].DOB.localeCompare(list[b].DOB))
  .map(k => { return { [k]: list[k] } }));

Result:

[
  {
    "Rob": {
      "DOB": "2016-07-09"
    }
  },
  {
    "John": {
      "DOB": "2017-02-01"
    }
  }
]
janos
  • 120,954
  • 29
  • 226
  • 236
  • The names and contents are just for demonstration purposes - this is not my actual object. – JayBee Nov 24 '17 at 20:17
  • @user1637466 Apply the same logic to your real names and content, and the demonstrated technique will work just as well. – janos Nov 24 '17 at 20:20