Sorting an array of objects with the sortBy method of Prototype

Here is an example of how easy it is to sort an array of objects using the Enumerable.sortBy method of the Prototype framework:

var obj1 = {
  lastName : "Lacava",
  firstName : "Alessandro"
};

var obj2 = {
  lastName : "Brown",
  firstName : "John"
};

var obj3 = {
  lastName : "Simpson",
  firstName : "Bart"
};

var arr = [obj1, obj2, obj3];

//order by last name
var sorted = arr.sortBy(function(obj) {
  return obj.lastName.toLowerCase();
}
);

var str = "";
sorted.each( function(obj, index) {
  str += index + 1 + " - " + obj.lastName + " " + obj.firstName;
}
);

//display the elements ordered by last name
document.write(str);
This entry was posted in IT, Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

2,103 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>