Reputation: 1779
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
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
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);
...
};
Upvotes: 0
Reputation: 5260
For more fun and cleaner code you may consider using lodash
contacts = _.sortBy(contacts, ['last_name', 'first_name']);
Upvotes: 1
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