# How to Sort Numeric Array using JavaScript ?

The JavaScript Array.sort() method is used to sort the array elements in-place and returns the sorted array. This function sorts the elements in string format. It will work good for string array but not for numbers. For example: if numbers are sorted as string, than “75” is bigger than “200”.

Example:

```Input          : [12, 25, 31, 23, 75, 81, 100]
Wrong Output   : [100, 12, 23, 25, 31, 75, 81]
Correct Output : [12, 23, 25, 31, 75, 81, 100]
```

Example: This example sorts the array elements in string format.

 ` `

Output:

```Original Array
12,25,31,23,75,81,100

After Sorting in Ascending Order
100,12,23,25,31,75,81```

Then, how to sort number array elements ?
There are two approaches to sort the number array in ascending order.

• Using Compare Function
• By Creating Loops

Using Compare Function: We can create a Compare function that return negative, zero, or positive values.
Syntax:

`function(a, b){return a - b}`
• Negative Value ( a > b) => a will be Place before b
• zero value (a == b) => No Change
• Positive Value (a < b ) => a will be place after b

Example: This example uses compare function to sort the array elements in ascending order.

 ` `

Output:

```Original Array
12,25,31,23,75,81,100

After sorting in Ascending order
12,23,25,31,75,81,100```

Now, we would like to sort the array in Descending order than we have to change the compare function.

Syntax:

`function(a, b){return b - a}`
• Negative Value ( b < a) => a will be Place after b
• zero value (a == b) => No Change
• Positive Value (b > a ) => a will be place before b

Example: This example uses compare function to sort the array elements in descending order.

 ` `

Output:

```Original Array
12,25,31,23,75,81,100

After sorting in Ascending order
100,81,75,31,25,23,12```

Creating Loops: We can also use loops to sort the array elements. Here, we will use bubble sort (simple sorting technique) to sort the array elements in ascending order.

Example:

 ` `

Output:

```Original Array
1,15,10,45,27,100

Sorted Array
1,10,15,27,45,100``` My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : Akanksha_Rai

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.