0

How can I sort the arr by created_at?

arr = [{1:{"created_at":3}}, {2:{"created_at":5}}, {3:{"created_at":2}}]

Desired result:

arr = [{3:{"created_at":2}}, {1:{"created_at":3}}, {2:{"created_at":5}}]

The problem is that the first key is different for each object and I want to access the object assigned to that key and then the .created_at property on that to sort, can someone help`?

Alex L
  • 4,168
  • 1
  • 9
  • 24
Jessica
  • 37
  • 1
  • 2
  • JS doesn't have "dictionaries"; that's a Python tthing. JS has objects (which in some respects are similar to, but in various respects also also very different from, Python dictionaries). You sort arrays in JS with `arr.sort()`, and if you need custom sorting, you pass a `function(a,b) { return negative, zero or positive number }` function where you get to write whatever code makes sense. – Mike 'Pomax' Kamermans Mar 22 '20 at 20:39
  • We can do it with: ``arr.sort((a,b) => Object.entries(a)[0][1].created_at - Object.entries(b)[0][1].created_at);`` I can't post the answer because it was closed. But I do have it working here too: https://codepen.io/Alexander9111/pen/vYOzzKq – Alex L Mar 23 '20 at 08:35

0 Answers0