I´m using sort() to order an Array by date
elements = data.sort(function(a, b) { return a.date.getTime() - b.date.getTime() }); the problem is that some elements are missing the date (or the date is invalid) and that´s causing this error:
Cannot read property 'getTime' of undefined
update: I have moment ready to use
Where should I check if date is valid date and then use it to order the array?
update: this is the data I have
[{ "date": "2019-06-15 14:57:13", "user": "john" }, { "date": "2019-06-15 05:48:01", "user": "mike" }, { "date": "bad-date-format", "user": "donna" }, { "date": "2019-06-08 10:45:09", "user": "Ismil" }, { "date": "", "user": "Daniel17" } ] and this is the output I expect
[ { "date": "2019-06-15 14:57:13", "user": "john" }, { "date": "2019-06-15 05:48:01", "user": "mike" }, { "date": "2019-06-08 10:45:09", "user": "Ismil" }, { "date": "bad-date-format", "user": "donna" }, { "date": "", "user": "Daniel17" } ]
sortsorts the array. an assignment takes just the same object reference.a - bgives ascending order. Do you really mean descending?getTimea method ofdateproperty? please add some data to proof the algorithms of the answers. if your callback works, why do you get a descending result by using the delta of a and b? please add the wanted result as well to the question (and not in comment section).