DEV Community

Liz P
Liz P

Posted on

Lets Get This Party Sorted-Sorting Arrays in JavaScript

It’s a pretty safe bet to say you’ll need to sort an array at some point. Why do we need to do sort arrays and how do we do that in JavaScript?

We can use the built-in sort method. The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Seems simple enough right? Well, sure you think a default of sorting in ascending order would give you exactly what you think but it can be a little more complex to really understand what sort does and what you’ll get back.

The best way to visualize sort() is to look at some examples. Let’s first take a look at an array of some grocery items, and we want to sort the array alphabetically:

let groceries = ['bread', 'oranges', 'zucchini', 'strawberries', 'cheese', 'milk']

groceries.sort()
console.log(groceries); // ['bread', 'cheese', 'milk', 'oranges', 'strawberries', ‘zucchini']
Enter fullscreen mode Exit fullscreen mode

That gives us what we’d expect. So great, easy. Well let’s look at something else.

Now, we want to sort an array of numbers. Again, nothing crazy, just ascending order:

let nums = [5, 245, 1000, 13, 1, 59]

// sorting in ascending order we expect to get back an array that looks like this [1, 5, 13, 59, 245, 1000]
// spoiler that's not what we'll get

nums.sort();
console.log(nums); // [ 1, 1000, 13, 245, 5, 59 ]
Enter fullscreen mode Exit fullscreen mode

Ok, that’s weird. What? Why? JavaScript interprets each element like a string and will compare elements one character unit at a time according to UTF-16 code units order i.e. the numbers in our nums array are sorted based off the first character of each number so 1000 came after 1, and 245 came before 5. This isn’t really useful. What do we do to get the expected result?

let nums = [5, 245, 1000, 13, 1, 59]

nums.sort((a, b) => a - b);
console.log(nums); // [ 1, 5, 13, 59, 245, 1000 ]
Enter fullscreen mode Exit fullscreen mode

Now we’re talking, the numbers are in the correct ascending order. What happened here? According to MDN, to compare numbers instead of strings, the compare function can subtract b from a. The following function will sort the array in ascending order (if it doesn't contain Infinity and NaN). We compare the numbers in the array using a function, an arrow function is used here to keep the syntax shorter.

Alright, now we can sort arrays of strings and arrays of number in ascending order. Guess what? We can also sort them in descending order.

Suppose we have a list of contacts but we have A LOT of contacts and we’re looking for someone with a name that begins with z. Instead of sorting in ascending order and looking all the way at the end of our array, we should just sort in descending order- z will come first.

let contacts = ['John', 'Steve', 'Kara', 'Tim', 'Bob', 'Jane', 'Amy', 'Mark', 'Kelley', 'Jared', 'Lauren', 'Tom', 'Lily', 'Zach', 'Aaron']

contacts.sort().reverse();
console.log(contacts); // ['Zach', 'Tom', 'Tim', 'Steve', 'Mark', 'Lily', 'Lauren', 'Kelley', 'Kara', 'John', 'Jared',  'Jane', 'Bob', 'Amy', 'Aaron'] 
Enter fullscreen mode Exit fullscreen mode

Back to our nums array, now we want descending order. We still need to compare the numbers but this time the function can subtract a from b. Here’s what that looks like:

let nums = [5, 245, 1000, 13, 1, 59]

nums.sort((a, b) => b - a);
console.log(nums); // [1000, 245, 59, 13, 5, 1]
Enter fullscreen mode Exit fullscreen mode

While the sort method is not as cut and dry as it first seems, it’s pretty powerful. I definitely suggest reading the MDN Web Docs to learn more about sort() and also playing around with some examples-trying to think about you’d expect the output to be and then running it in the console and see if it’s what you actually get. Thanks for reading!

Top comments (0)