-3

I tried to sort object by date. I must use es5 because it's in angularjs This is what I tried but no luck.

let objtemp = {
  1: {
    first: 0,
    created: "2020-11-03T14:16:51.319Z"
  },
  2: {
    first: 2,
    created: "2020-11-03T14:01:32.084Z"
  },
  3: {
    first: 2,
    created: "2020-11-03T14:00:47.000Z"
  }
};
let temp = Object.entries(objtemp);
temp.sort(function([a, aval], [b, bval]) {
  return new Date(bval.created).getTime() - new Date(aval.created).getTime();
});
console.log(temp);

The result I get :

{1:{first:0, created: "2020-11-03T14:16:51.319Z"}, 2:{first:2, created: "2020-11-03T14:01:32.084Z"}, 3:{first:2, created:"2020-11-03T14:00:47.000Z"}}

Expected result is

{3:{first:2, created:"2020-11-03T14:00:47.000Z"},2:{first:2, created: "2020-11-03T14:01:32.084Z"},1:{first:0, created: "2020-11-03T14:16:51.319Z"}}
epascarello
  • 204,599
  • 20
  • 195
  • 236
Emilis
  • 152
  • 1
  • 4
  • 21
  • https://stackoverflow.com/questions/1069666/sorting-object-property-by-values read this blog – Nbody Nov 03 '20 at 14:33
  • *"The result I get"* That definitely isn't the result you get, because you've logged `temp`, which is an array, but you've shown a non-array object. – T.J. Crowder Nov 03 '20 at 14:33
  • Why is the input an object with "numeric" keys and not an actual array? – Andreas Nov 03 '20 at 14:33
  • 1
    Your sort check is opposite of what you need.... `return new Date(aval.created).getTime() - new Date(bval.created).getTime();` – epascarello Nov 03 '20 at 14:35
  • 1
    Side note: A more concise way to write `new Date(x).getTime()` (where `x` is a string) is `Date.parse(x)`. They do the same thing, the latter is just less work. – T.J. Crowder Nov 03 '20 at 14:35
  • @T.J.Crowder The OP is sorting an array... not sure what object has to do with it... – epascarello Nov 03 '20 at 14:36
  • @epascarello thanks your answer is correct – Emilis Nov 03 '20 at 14:36
  • @Andreas that is the type of data I get so I have to sort it and I use Object.entries for that – Emilis Nov 03 '20 at 14:38
  • @epascarello - By the time they do the `sort`, yes. But the headline question is *"How to sort nested obj javascript"* so I figured the array was a temporary intermediary, esp. given the "expected result" is also a non-array object. But by all means, add a dupetarget for sorting an array of objects by a date property. Plenty to choose from. :-) – T.J. Crowder Nov 03 '20 at 14:38

1 Answers1

0
temp.sort(function([a, aval], [b, bval]) {
  return new Date(aval.created).getTime() - new Date(bval.created).getTime();
});

Problem was the sort check was opposite to what I needed. Thanks to @epascarello

Emilis
  • 152
  • 1
  • 4
  • 21