-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"}}
9
  • stackoverflow.com/questions/1069666/… read this blog Commented Nov 3, 2020 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. Commented Nov 3, 2020 at 14:33
  • Why is the input an object with "numeric" keys and not an actual array? Commented Nov 3, 2020 at 14:33
  • 1
    Your sort check is opposite of what you need.... return new Date(aval.created).getTime() - new Date(bval.created).getTime(); Commented Nov 3, 2020 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. Commented Nov 3, 2020 at 14:35

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.