Site icon Treehouse Blog

JavaScript Array Methods: sort()

Ever found yourself needing to sort an array? This could be strings being sorted in alphabetical order or even a players’ scores from highest to lowest. Whichever the case may be, the JavaScript sort() method can make this task easy. Follow along as I go over how to use this array method!

According to W3School:
The sort() method sorts an array alphabetically.

Seems easy enough right? Let’s put it into practice.

Consider the following array:

const months = ['January', 'April', 'July', 'December']

Let’s run our sort() method on this array and see what we get back.

console.log( months.sort() );

// expected output: ['April', 'December', 'January', 'July']

Pretty neat, we can see it easily sorted our array in alphabetical order! What about numbers? Can sort() work with number-types? Let’s find out.

Consider the following array:

const numbers = [10, 5, 100, 53, 6]

What do you think happens if we run our sort() method on this numbers array? Lets try it!

console.log( numbers.sort() );

// expected output: [10, 100, 5, 53, 6]

Welp, the array changed, but something doesn’t look right, does it? Let me explain what happened. The sort() method will attempt to convert the array items to strings, sort the array items, then convert them back to numbers. So when this happens, they are being sorted as strings.

To sort numbers in an easier way with more control, we can use what’s known as the compare function with our sort() method.

According to W3Schools:

The purpose of the compare function is to define an alternative sort order. The compare function should return a negative, zero, or positive value, depending on the arguments.

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

If the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, no changes are done with the sort order of the two values.

Lets put this into action and try to sort our numbers array again.

const numbersInOrder = numbers.sort((a, b) => a - b);
console.log(numbersInOrder);

// expected output: [5, 6, 10, 53, 100]

Great! Looks like we were able to sort the numbers from lowest to highest. What’s happening is that through each iteration of our array, a is compared to b and if the result is negative, a will be sorted before b. If the result is positive, b will be sorted before a.

So what if we wanted to sort the array from highest numbers to lowest numbers? Simple, just reverse the logic. Instead of a - b we can write b - a.

const numbersInOrder = numbers.sort((a, b) => b - a);
console.log(numbersInOrder);

// expected output: [100, 53, 10, 6, 5]

Consider our students array. It contains an array of objects:

const students = [
    {
        name: 'Alex',
        points: 31224,
        badges: 74
    },
    {
        name: 'Taylor',
        points: 16273,
        badges: 32
    },
    {
        name: 'Jamie',
        points: 33298,
        badges: 56
    }
]

Lets say we wanted to sort this array by students with the most amount of badges to the student with the least amount of badges. We can write the following:

const mostBadges = students.sort((a, b) => b.badges - a.badges);
console.log(mostBadges);

// expected output: [
    { name: 'Alex', points: 31224, badges: 74 },
    { name: 'Jamie', points: 33298, badges: 56 },
    { name: 'Taylor', points: 16273, badges: 32 }
]

Pretty easy! You can see we used b.badges - a.badges to return back our array items with the higher badge counts first.

What about strings? We saw earlier how easily we can sort strings alphabetically with a simple array but what about with an array of objects? Lets sort these array items based off the name property in alphabetical order.

const sortedByName = students.sort((a, b) => {
    if (a.name > b.name) return -1
    return 1
});
console.log(sortedByName);

// expected output: [
    { name: 'Taylor', points: 16273, badges: 32 },
    { name: 'Jamie', points: 33298, badges: 56 },
    { name: 'Alex', points: 31224, badges: 74 }
]

Uh oh, looks like we get it back in reverse order. Remember earlier when we went over the compare function?

If the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, no changes are done with the sort order of the two values.

So let’s change our return statement just a little. Instead of the first part of our condition returning -1, lets have it return 1 and vice-versa.

const sortedByName = students.sort((a, b) => {
    if (a.name > b.name) return 1
    return -1
});
console.log(sortedByName);

// expected output: [
    { name: 'Alex', points: 31224, badges: 74 }
    { name: 'Jamie', points: 33298, badges: 56 },
    { name: 'Taylor', points: 16273, badges: 32 },
]

Pretty simple!
I am using a positive and negative 1 but you can use any value you’d like. Just make sure one is positive and the other is negative.

I hope this guide on using the sort() method allows you to comfortably sort your arrays while building your next big dream project. I’ll see you in the next one. Until then, have fun and happy coding!

Exit mobile version