I get back a json object from Facebook which contains some friends information.
Some users have included their birthday some have not, while others have included only the the month and day.
I want to sort the array putting users with a birthday that is closes to the current date first.
How can I do this?
The json object looks like this:
json = { "data" : [{name : "Joe Sam", id : "5555555", birthday: "02/02/1989" }, {name : "Joe Sam", id : 5555555, birthday: }, {name : "Joe Sam", id : 5555555, birthday: "01/01" }
Your JSON is invalid – if that is the actual JSON string keynames need to be quoted. You have left off the closing ] and }, and the middle record’s birthday has to have some kind of value, e.g., empty string or null – or just don’t provide that key at all. I’ll assume you can fix that and will have already parsed the JSON into a variable called
json.Also you don’t say if the dates are in DD/MM(/YYYY) format or MM/DD(/YYYY) format so I’ll code for DD/MM but you can comment that out to use MM/DD instead.
“Closest to the current date” is ambiguous: is yesterday closer than next week? I shall assume that yesterday is as far from the current date as you can get.
So here’s your object tidied up along with a sort routine. I haven’t tested it, but even assuming it is broken it should give you the general idea:
For details about how
.sort()works refer to the MDN doco.