3

I need to sort an object array by date values:

array.sort(function(a,b){
return new Date(b.date) - new Date(a.date);
})

But if date is undefined, it should be placed at the beginning. With my code shown above, the empty datasets will be placed at the end.

9
  • sounds like the quick and dirty would be to just reverse the array?... array.sort(/* ...other code here... */).reverse() Commented Dec 29, 2019 at 1:21
  • @MattOestreich No, as the sorting of all other elements should not be reversed Commented Dec 29, 2019 at 1:21
  • Gotcha.. well damn was hoping that would help.. Commented Dec 29, 2019 at 1:22
  • What are the possible values for the date field? Is it expected to be string or integer? Commented Dec 29, 2019 at 1:24
  • @MisterJojo that's why I asked about the input. The Date constructor also supports strings Commented Dec 29, 2019 at 1:29

1 Answer 1

4

const array = [
  { date: 624000, name: 'Eddison', },
  { date: 224000, name: 'Bobby', },
  {               name: '--no date 2' },
  { date: 924000, name: 'Fred', },
  { date: 124000, name: 'Abe', },
  {               name: '--no date 1' },
  { date: 424000, name: 'David', },
  { date: 324000, name: 'Catheryn', },
];

// assuming there is no 0 date
array.sort(function(a, b) {
  return (a.date && b.date)
      ? new Date(b.date) - new Date(a.date)
      : (a.date || 1) - (b.date || 1); 
});

//result
array.forEach(elem => console.log(JSON.stringify(elem)));

note if you care about the difference between a date of 0 and a undefined date then

  return (a.date !== undefined && b.date !== undefined)
Sign up to request clarification or add additional context in comments.

12 Comments

your a and b are numbers, no need to convert them to dates to make a sort...
Of course but the OP didn't show what their dates were and numbers work just fine as place holders for whatever they had.
Note that the OP clarified they have ISO date strings
@HubertGrzeskowiak yep you are correct, I just tested in Chrome and it works.. This does not appear to work in Firefox.. whew, I was going crazy for a second there lol. Thank you so much for helping me grasp this!
this code is OK on Chrome, but wrong on FireFox
|

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.