DEV Community

Cover image for Sorting an Array of Number Strings in JavaScript
El Marshall (she/they)
El Marshall (she/they)

Posted on

Sorting an Array of Number Strings in JavaScript

Okey dokey, the binary tree hiatus continues, because my node deletion post got out of hand and I need to get a post up in the next couple hours and I am tired y'all.

So I'm gonna write a quick post about a function in JavaScript that I found really confusing for a long time - I guess no one satisfactorily explained to me what was going on, so it just looked like gibberish.

You ask the internet how to sort an array of numbers in JavaScript, and they'll tell you this:

arr.sort(function(a, b){return a-b});

Honestly my brain looked at that and went... Huh?
Ultimately it really is not very difficult, but no one had properly explained to me why each piece of this does what it does. So I'm gonna lay it out.

First, the basics of the JavaScript sort method. The language has a built in function sort() that can be applied to an array. Take for example, this array of integers:

let arr = [2, 6, 3, 8, 54, 846, 4]
arr.sort()
console.log(arr) // [2, 3, 4, 6, 8, 54, 846]

That did just what you expected, really. Now we'll apply it to an array of strings:

let arr = ['cat', 'monkey', 'apple', 'apples']
arr.sort()
console.log(arr) // ['apple', 'apples', 'cat', 'monkey']

You can even mix integers and string representations of numbers, like so:

let arr = [2, "6", 3, "8", 54, 846, 4]
arr.sort()
console.log(arr) // [2, 3, 4, "6", "8", 54, 846]

But there's a wrinkle. See what happens to the following array:

let arr = ["8", "4", "54"]
arr.sort()
console.log(arr) // ["4", "54", "8"]

Because it's comparing these elements as strings, not integers, "54" comes before "8" because it starts with "5". That's probably not what you were going for. Let's take another look at that fancy nonsense from above now:

arr.sort(function(a, b){return a-b});

The problem I had upon first seeing this was that I was trying to interpret this logically, reading the code on its face. I didn't realize this is a case of another built in method for JavaScript. The function is actually an optional parameter, called the compareFunction, that allows you to define an alternative sort order.

Per the W3schools page on the subject,

When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

The magic is that by performing an operation (subtraction) on the numbers in question, JavaScript converts them to integers. So it receives "54" and 4 and returns 54 - 4. That's a positive number, so the sort method knows to put 4 first. If you wanted to sort in descending order, you could use this instead:

arr.sort(function(a, b){return b-a});

Personally I think this is some pretty clunky syntax to remember, but it's what we've got!

Top comments (4)

Collapse
 
dyrpit profile image
Piotr Dyrda

Well the result of this example is incorrect:

let arr = [2, 6, 3, 8, 54, 846, 4]
arr.sort()
console.log(arr) // [2, 3, 4, 6, 8, 54, 846]

The output will be [2, 3, 4, 54, 6, 8, 846]. This happens because when you use just .sort(), it defaults to sorting elements as if they were strings, leading to an alphabetical order rather than a numerical one.

Collapse
 
shokhrukh1212 profile image
shokhrukhKarimov

This will return a correct answer for all string numbers array
arr = ["9", "20", "1", "75", "34", "100"]

arr.sort((a, b) => {
    if (a.length !== b.length) {
      return a.length - b.length;
    }
    return a.localeCompare(b);
  });
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sifr-in profile image
masoom nazir sanadi • Edited

subscribed "dev.to",
just to like your solution.

Collapse
 
depranecdote profile image
depranecdote

The third example, which combines integers and strings, is incorrect because "6" would appear after "54", as "5" comes before "6" lexically.