0

There is an array emails having few attributes To, From, Subject, Description. I retrieve records from database and populate all rows in this array. I use to access all rows as follows:

 for (var i = 0; i < emails.length; i++) {
    var To = emails[i].To;
    var Sender = emails[i].Sender;
    var Subject = emails[i].Subject;
    var Description = emails[i].Description;
 }

Now I need to sort this array alphabetically by To values and store the sorted emails in another array sortedemails. How can I do this in easiest possible way in Javascript/JQuery?

Thanks.

Azeem
  • 2,904
  • 18
  • 54
  • 89

2 Answers2

2

Arrays in javascript have a sort function.

emails.sort(function(a, b) { 
   if (a.To < b.To) {
     return -1;
   } else {
      return 1;
   }
}
Matt R
  • 724
  • 5
  • 14
0

JavaScript arrays have a built-in .sort method. No loops (or jQuery needed).

emails.sort(function(a, b){
    return a.To.localeCompare(b.To);
});

This will modify the email array. If you want to save the original (unsorted) array, you'll need to copy the array before sorting.

var sortedemails = emails.slice(0);
sortedemails.sort(function(a, b){
    return a.To.localeCompare(b.To);
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337