Rich
Rich

Reputation: 1779

Phonegap contact sort order on ios

Does anyone know how to sort the contact data that phonegap liberates from iOS to javascript. The order at the moment is nothing to do with alphabetical sorting. I want to sort on last name.

Here is my contact code:

function init_contacts() {
     var fields = [ "name","phoneNumbers"];
     navigator.service.contacts.find(fields, contactSuccess, contactError, '');
}
function contactSuccess(contacts) {
    for (n = 0; n < contacts.length; n++) {
        if (contacts[n].phoneNumbers) {
            for (m = 0; m < contacts[n].phoneNumbers.length; m++) {
                addToMyContacts(contacts[n].name.formatted, contacts[n].phoneNumbers[m].value);
                console.log('Found ' + contacts[n].name.formatted + ' ' + contacts[n].phoneNumbers[m].value);
            }
        }
}
$("#my_contacts").listview("refresh"); 
};

function contactError() {
    navigator.notification.alerter('contactError!');
};

Upvotes: 2

Views: 3227

Answers (4)

hayesgm
hayesgm

Reputation: 9096

You can do this sort by hand in Javascript.

var cSort = function(a, b) {
  var aName = a.lastName + ' ' + a.firstName;
  var bName = b.lastName + ' ' + b.firstName;
  return aName < bName ? -1 : (aName == bName ? 0 : 1);
};

function contactSuccess(contacts) {
  contacts = contacts.sort(cSort);
  ...
};

Upvotes: 5

tormuto
tormuto

Reputation: 585

I am using this method, which is far more efficient (compared to the accepted answer)

var cSort=function(a,b){ 
        var an=a.name.formatted.toUpperCase();
        var bn=b.name.formatted.toUpperCase();
        return (an<bn)?-1:(an==bn)?0:1;
    };

function contactSuccess(contacts) {
  contacts = contacts.sort(cSort);
  ...
};
  1. Contact.name.formatted is more consistent across platforms
  2. All names starting with the same letter will be grouped together irregardless of the case. (you can also try it to see).

Upvotes: 0

guya
guya

Reputation: 5260

For more fun and cleaner code you may consider using lodash

contacts = _.sortBy(contacts, ['last_name', 'first_name']);

Upvotes: 1

Darshan
Darshan

Reputation: 2379

sorting in js

function sortByitemName(a, b) { var x = a.displayName.toLowerCase(); var y = b.displayName.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }

function onSuccess(contacts) {

contacts.sort(sortByitemName);

 }

Upvotes: 0

Related Questions