Rearranging Array Data — The .sort() Method

Matt Eva
6 min readNov 17, 2021

(JavaScript + React Tutorials)

Arrays are invaluable data structures in JavaScript. They have an incredible number of unique methods (including the frequently used .filter(), .map(), and .reduce()), can be easily iterated, and see a lot of use in React applications.

Oftentimes, we receive data from our servers in the form of an array. While sorting and arranging data can be done server side, there will probably be some instances in which we’ll want to sort or manipulate data on the front end (i.e. using JavaScript or React). The .sort() method is a handy and flexible tool that can be used when sorting data on the front end.

The .sort( ) Method

.sort() is a method unique to arrays, and its function is pretty self-explanatory — it sorts the data within your array. How it sorts that data, however, is up to you. We’ll cover both alphabetical sorting and numerical sorting as examples.

First and foremost, however, is the syntax for the sort method. Sort takes a callback function as its argument, which makes it pretty flexible. Sort doesn’t have to take a callback function, but without a callback, its functionality is pretty limited.

For example, if we call sort on an array of strings without giving it a callback function, it will rearrange that array to be in alphabetical order — the strings whose first letters are earlier in the alphabet will be assigned a lesser index value. The name Aaron, for example, would almost always have an index of 0 in an array of strings that had been sorted in this manner. Ex:

It’s important to note that calling sort on an array modifies that original array. If you don’t want to modify your original array, you’ll want to spread your array, call sort on the spread, and assign that sorted version of the spread to a new variable. Ex:

Calling sort on an array of numbers without a callback function can cause some problems. Because the sort method looks at the value of each individual numeral within a number, as opposed to the value of the entire number, a number whose first numeral is less than the first numerals of other numbers will always be given lesser index values, even if its actual value is far greater. This applies for each numeral comparison between two numbers. Ex:

This problem can be solved when implementing a callback function, as we’ll see in a moment.

.sort( ) and Callback Functions

You can pass callback functions to sort in three main ways. With an arrow function:

With a standard function declaration:

Or by writing your function outside of your .sort() and passing it as a callback:

Using any of these syntaxes works great. I like using the arrow function syntax for simple sort operations, but for more complex sorting, it’s occasionally helpful to write my function outside of my sort and pass that function reference as a callback.

You’ll notice that all of these functions have two parameters — a and b. You can think of these as your a valueand your b value. Essentially, parameter a represents one element within your array, while parameter b represents another element within your array.

The examples I’ve shown above are handling a numerical sort, and are sorting by lesser to greater numbers. (sortedNumArray will equal [2, 30, 120, 1050] in each example). This has to do with the nature of our return statement. If our a — b operation results in a negative value, a will be sorted before b. If it results in a positive value, b will be sorted before a. If it results in a value of 0, a and b will not change positions. This functionality is built into the sort method, and can be used in creative ways to sort a variety of array elements.

Creative Sorting

Before we go into these next examples, let’s cover a helpful tip about comparing strings. We can actually use the greater than — >— and less than — <— operators to compare two strings. If we were to place strings in alphabetical order, strings that evaluated to “less than” would be placed before strings that evaluated to “greater than”. Ex:

We can use this knowledge in conjunction with conditional statements and the .sort() method’s treatment of negative, positive, and zero values to creatively handle a variety of sorting operations.

For example, let’s say we have an array of objects. These objects contain information about people, and have a key of name that points to each person’s name. Our array contains these person objects in no particular order — we want to sort them alphabetically based on the name associated with each person object. Here’s how we can go about doing that:

Let’s break this down. First, we’re declaring a new variable, alphabetizedPeople, that will reference our new, alphabetical array. Then, we’re spreading our people array so that we don’t sort our original people array (maybe we’re using it for something else). Next, we’re calling sort on our spread of people array. Finally, we have our callback function, which takes parameters a and b (a element and b element).

Within our callback function we have a conditional statement. Our first conditional is checking to see if the name in our a element is “less than” the name in our b element (i.e. should it appear earlier in alphabetical order). Notice we’re using dot notation to access the key “name” of both our a element and b element. We can do this because each element in our people array is an object that has a key of “name” in it.

If this first conditional evaluates to true, we’re going to return -1, which tells sort to sort element a before element b. If it evaluates to false, we move on to our next conditional.

Our next conditional checks to see if the name in element a is “greater than” the name in element b, i.e. if it should come after b.name in alphabetical order. If this conditional evaluates to true, we return 1, which tells our sort to place element a after element b.

Finally, if neither of these conditionals evaluates to true — which will occur if the name in each element is identical — we return 0, which tells our sort to leave these elements in the order in which they already are.

Conclusion

This has been a basic overview of how to use the array .sort() method — hope it was helpful! Happy sorting.

--

--

Matt Eva

I write about coding, web development, and various other programming topics!