Search code examples
javascriptlodash

Sort Array of Nested Objects by Dynamic Key


I believe I'm wording this question correctly.... I have a dataset like this...

[
  {
    "Fri Aug 03 2018 00:00:00 GMT-0500": {
      "bill": "Test 2",
      "account": "defaultAccount",
      "amount": 40,
      "category": "defaultCategory",
      "description": "231"
    }
  },
  {
    "Fri Aug 17 2018 00:00:00 GMT-0500": {
      "bill": "Test 2",
      "account": "defaultAccount",
      "amount": 40,
      "category": "defaultCategory",
      "description": "231"
    }
  },
  {
    "Wed Aug 01 2018 00:00:00 GMT-0500": {
      "bill": "test",
      "account": "create-account",
      "amount": 40,
      "category": "mortgage",
      "description": "23"
    }
  }, ....
]

and I'm struggling to sort the array based on the object's dynamic date. I've spent the last few hours going through every version of this question on stack overflow and I'm not coming up with a solution... any advice is greatly appreciated!


Solution

  • You need to get the key of each outer object and get a date object. Then take the delta for sorting.

    var array = [{ "Fri Aug 03 2018 00:00:00 GMT-0500": { bill: "Test 2", account: "defaultAccount", amount: 40, category: "defaultCategory", description: "231" } }, { "Fri Aug 17 2018 00:00:00 GMT-0500": { bill: "Test 2", account: "defaultAccount", amount: 40, category: "defaultCategory", description: "231" } }, { "Wed Aug 01 2018 00:00:00 GMT-0500": { bill: "test", account: "create-account", amount: 40, category: "mortgage", description: "23" } }];
    
    array.sort((a, b) => new Date(Object.keys(a)[0]) - new Date(Object.keys(b)[0]));
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }