Use a custom sort function on an Array in Javascript

InstructorChris Achard

Share this video with your friends

Send Tweet

Sorting in Javascript with sort uses lexical sorting by default, which means it will sort in alphabetical order. That's fine for strings of characters, but it means that arrays of numbers don't sort in numerical order! To fix that, we'll pass a custom comparator function to sort. The function you pass to sort will be passed two values from the array at a time, and should return a value <0, =0 or >0, based on which value should be sorted first in the final array.

Once you have a custom sort function implemented, you can sort in any way that you'd like. We'll show that by pulling out just part of a string, and sorting based on that value.