Rich Rich - 8 days ago 4
iOS Question

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!');
};

Answer

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);
  ...
};