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.

2
  • alphabetically by To ? Commented Apr 4, 2014 at 15:23
  • 1
    first link is the answer to your question Commented Apr 4, 2014 at 15:24

2 Answers 2

2

Arrays in javascript have a sort function.

emails.sort(function(a, b) { 
   if (a.To < b.To) {
     return -1;
   } else {
      return 1;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.