Phonegap contact sort order on ios
Does开发者_C百科 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!');
};
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);
...
};
For more fun and cleaner code you may consider using lodash
contacts = _.sortBy(contacts, ['last_name', 'first_name']);
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);
}
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);
...
};
- Contact.name.formatted is more consistent across platforms
- All names starting with the same letter will be grouped together irregardless of the case. (you can also try it to see).
精彩评论