avatarDr. Derek Austin 🥳

Summary

This context explains how to sort an array of numbers numerically in JavaScript using the sort() method and a comparison function.

Abstract

The context begins by explaining the default behavior of the sort() method in JavaScript, which sorts elements in an array in lexicographical (alphabetical) order, not numerical order. This means that when sorting an array of numbers, the sort() method will not produce the expected result. To achieve a numerical sort, a comparison function must be passed to the sort() method as a parameter. The comparison function should return a negative value if the first item is smaller, a positive value if the first item is larger, and 0 for equality. The context provides examples of how to use the comparison function to sort an array of numbers in both ascending and descending order. It also explains how to protect the original array from being modified by the sort() method by using the slice() method, the spread operator, or the Object.assign() method.

Bullet points

  • The sort() method in JavaScript sorts elements in an array in lexicographical order by default.
  • To achieve a numerical sort, a comparison function must be passed to the sort() method as a parameter.
  • The comparison function should return a negative value if the first item is smaller, a positive value if the first item is larger, and 0 for equality.
  • Examples of how to use the comparison function to sort an array of numbers in both ascending and descending order are provided.
  • The slice() method, the spread operator, or the Object.assign() method can be used to protect the original array from being modified by the sort() method.

How to sort an array numerically in JavaScript

The default ECMAScript sort is alphabetical, so a little magic is needed to sort an array in numerical order.

Photo by Sora Sagano on Unsplash

Ever try to sort an array of integers in JavaScript using .sort() and get a weird result, where the order was not numeric?

What is going on here?

The array got sorted in lexicographical order (that is, alphabetically), so each integer actually got coerced into a string type.

Then each string was compared, which is why -10 came before -14 and 23 came before 3 — strings are compared character-by-character.

The solution to achieve a numeric sort is passing a comparison function to the .sort() method as a parameter.

Photo by Elliot Banks on Unsplash

Use .sort((a,b) => a-b)

In order to sort a list in numerical order, the Array.prototype.sort() method needs to be passed a comparison function.

To sort the array numerically in ascending order, That comparison function should return the difference between the two numbers.

This is achieved by subtracting the second item from the first.

That’s more like it!

The (a,b)=>a-b comparison function subtracts the second item from the first item, thus returning a negative value if the second item is bigger, a positive value if the second item is smaller, and 0 for equality.

Photo by Mark Tegethoff on Unsplash

Descending numerical sort

A descending sort would just need the operators reversed, so the comparison function becomes (a,b)=>b-a:

Photo by Anthony DELANOIX on Unsplash

Protecting the original with .sort()

In addition to returning the sorted array, the .sort() method sorts the array in-place, changing the value stored for that variable.

Since arrays are objects in JavaScript, their contents can still be changed even if they are created using the const keyword.

So, there needs to be a way to keep the original array intact and prevent it from being changed. One way is using Array.prototype.slice():

Other options are using the spread operator () or Object.assign() :

Photo by Shawnn Tan on Unsplash

Conclusion

Sorting an array in JavaScript is actually pretty powerful because of how comparison functions work: -1 for <, 0, and 1 for >.

That being said, it is pretty confusing that the default sort is always alphabetical… even when the array has numbers in it, not strings.

We can use .sort((a,b)=>a-b) to sort an array of numbers in ascending numerical order or .sort((a,b)=>b-a) for descending order.

The .sort() method sorts the array in-place, so if necessary we can make a copy while sorting by using the syntax […array].sort() .

Get out there and sort some arrays! You can do it!

Photo by Daniel Hehn on Unsplash

Further reading

  • Alligator.io published an article about sorting arrays of numbers:
  • RadDevon.com also has an article about sorting arrays of numbers:
Photo by Banter Snaps on Unsplash

Dr. Derek Austin is the author of Career Programming: How You Can Become a Successful 6-Figure Programmer in 6 Months, now available on Amazon.

JavaScript
Programming
Technology
Software Engineering
Data Science
Recommended from ReadMedium