Sorting birthdays received from Facebook’s graph API

While working with Friend lists using Facebook’s graph API, you may want to retrieve your friends and do something based on their birthdays. Here’s some sample code to sort your friends based on upcoming birthdays.

FB.api("/me/friends?fields=id,name,birthday,picture, link", dojo.hitch(this, function(response) {
    var birthdays = response.data; //list of friend objects from facebook
    var currentMonth = new Date().getMonth() + 1;
    var upcoming = [];
    dojo.forEach(birthdays, function(item) {
        if (item.birthday) {
            var bday = item.birthday;
            //if the birthday is after today
            if (currentMonth <= bday.substr(0, 2) * 1 && new Date().getDate() <= new Date(bday).getDate()) {
                upcoming.push(item);
            }
        }
    });

    //set the year to current year because of birth years being different.
    var year = new Date().getFullYear();
    upcoming = upcoming.sort(function(a, b) {
        return new Date(a.birthday).setYear(year) - new Date(b.birthday).setYear(year);
    });

    console.log(upcoming);//console log here, but do whatever you want with the sorted friends
}));
Advertisements

4 thoughts on “Sorting birthdays received from Facebook’s graph API

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s