JavaScript Sort

Michael Abe
2 min readNov 25, 2021

One of the most important and basic aspects of programming using arrays to store and manage data. Since an array is basically a grouping or listing of data, as one can imagine, navigating through and sorting that data could potentially come in handy. There are a few ways to go about that but one of the easiest is the built in JavaScript .sort() method. The .sort() Method in application is chained on the end of an array and will return the sorted array (default is ascending) order. The most basic example of using a sort would be to rearrange numbers in ascending order. If we wanted to take people’s heights in inches and sort them, it would look like the following.

The is a very basic example but all we are doing is creating an array called “height” and then chaining the .sort() method to it. As we can see when log out our “height” array to the console, the array itself is now ascending in numerical value. The default sort is from low to high but as you can see if we send the .sort() method an anonymous function and ask it to return “b-a” instead of “a-b” we get the inverse, as we can see, the console is now listing our numbers in decrementing order.

This is obviously a surface level implementation of an powerful JavaScript method. There are many ways to use and fine tune the way that you sort in JS. In future instillations we will go over this more in-depth along with exploring some similar methods that you can use to streamline your code.

--

--