# How to Sort Numeric Array using JavaScript ?

• Last Updated : 27 Jan, 2022

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.

## javascript

 ``

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.

## javascript

 ``

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.

## javascript

 ``

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:

## javascript

 ``

Output:

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

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :