Sorting By Functions in JavaScript
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in JavaScript.
In this JavaScript version:
We use the built-in
sort
method for arrays, which accepts a comparison function.The comparison function
lenCmp
for string lengths is implemented as an arrow function that returns the difference in lengths.We sort the
fruits
array usingfruits.sort(lenCmp)
.For sorting custom objects, we define a
Person
class instead of a struct.We sort the
people
array using an inline arrow function that compares ages.
To run this program, you can save it as a .js
file and run it with Node.js:
Note that JavaScript’s sort
method modifies the original array in place, unlike some other languages where sorting returns a new array.