How to sort an array - JavaScript

Mo Ibra

Mo Ibra

Dec 26, 2022

In this article we will learn how to sort an array in JavaScript.

It is very common to sort an array in JavaScript in JavaScript.


Problem

Now we have a problem that we want to sort our array, but how do we do that?

First, imagine we have an array like this:

const array = [1, 3, 2, 5, 6, 4];

And we want to sort that array to be like this:

[1, 2, 3, 4, 5, 6]

How to solve this problem?

Solving this problem is easy, especially since there is a function called sort.

Sort an array using sort method

As we said before, we can use sort to sort elements in array.

Example

const array = [1, 3, 2, 5, 6, 4];
const sort = array.sort();
console.log(sort);

Output

[1, 2, 3, 4, 5, 6]

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: