# How to sort an array in JavaScript – ascending and descending

November 14, 2021

## How to sort an array in JavaScript – ascending and descending

In this article, we’ll learn how to sort an array in JavaScript, ascending and descending, using the JavaScript language.

What’s up, programmer, how are you? Let’s learn something new?

## Watch this content on YouTube:

Sorting arrays is a very simple task using JavaScript, we can use the sort method for that.

But it’s not always enough, so there’s a possibility to add a function as a parameter.

And with this function we can make a comparison between the values and sort the elements of an array

Both upwards and downwards

So let’s see in practice the code on how to sort arrays:

```let numbers = [5,32,1,838,34,2,5,9,8,2,98,42,64];

let numbersAsc = numbers.sort(function(a, b) {
return a - b;
});

console.log(numbersAsc); // [1, 2, 2, 5, 5, 8, 9, 32, 34, 42, 64, 98, 838]```

In this example we create an array with random numbers

After that, we apply the sort method with the anonymous function that I commented on earlier.

The function makes a comparison between the two values, a and b, so it checks which of them is greater or lesser and organizes the array. Isn’t that cool?

So we were able to order the array in ascending order, which I inserted into a new variable and printed to the console

## What if we want to sort an array in JavaScript in descending order?

We can use almost the same structure for this, just one more detail will solve the problem

Instead of comparing a – b, let’s do b – a

This will ensure that the largest number comes to the beginning and the smallest to the end, making it sort the array in descending order:

```let numbers = [5,32,1,838,34,2,5,9,8,2,98,42,64];

let numbersDesc = numbers.sort(function(a, b) {
return b - a;
});

console.log(numbersDesc); // [838, 98, 64, 42, 34, 32, 9, 8, 5, 5, 2, 2, 1]```

When I first saw this simple way to sort arrays, I also thought it was magic.

But it really works!

Conclusion

We learned that we can order arrays in JavaScript very simply

We use the sort method for this, with a function to help us compare array values

Subscribe
Notify of

Inline Feedbacks
0