Sorting a JavaScript array of strings or numbers is easy with the Array.sort() method. But what if you need to sort an array of custom objects?
The following code stanza shows an array (items) that will be populated with instances of a custom JavaScript object (MyItem).
Now, suppose that we want to sort the array alphabetically based on the title of our custom objects. We can prepare a function as such:
Now, we can sort the array of custom objects by passing the sort function into the Array.sort() method as follows:
The sorter function uses the a,b parameters to represent two objects being compared in the array. In this case, the two objects are instances of our MyItem class, so we can access properties of the instance (e.g. a.title or b.title) within the function.
Add Comment