How to use JavaScript Array Sort Method

Hey, after a long gap i am posting a content related to sorting array data using JavaScript this one came in mind when I was working in a JavaScript project. Yes using JavaScript you can order the array data in ascending or descending.

array sort, Javascript, javascript add to array, javascript array push, javascript array sort, javascript array to string, javascript join, javascript object to string, javascript reverse array, javascript sort, javascript sort array of objects, javascript sort function, sort
JavaScript Array Sort Method

But how its possible in JavaScript ?

Yes its possible using JavaScript `sort` method.

Let’s step into the code part.

// Create the variable and assign array elements
var arrData = ["PHP","ASP","NodeJS","Python"]

// Sorting the array elements using the sort method
document.write(arrData.sort())

// Sort method return the data output ` ASP,NodeJS,PHP,Python `

Now lets check it for numbers

// Create the variable and assign array elements
var arrData = [89,3,4,12,34]

// Sorting the array elements using the sort method
document.write(arrData.sort())

// Sort method return the data output ` 12,3,34,4,89 `

Sort method order the value as string, it’s work fine for string but if its number. sorting it will return incorrect data for the numbers. To overcome this issue we need to use compare function.

Ascending the array element

// Create the variable and assign array elements
var n = [89,3,4,12,3]

// Sorting the array elements using sort method
document.write(n.sort(function(a,b) { return a - b }));

// Sort method return the data output ` 3,4,12,34,89 `

Descending the array element

// Create the variable and assign array elements
var n = [89,3,4,12,3]

// Sorting the array elements using sort method
document.write(n.sort(function(a,b) { return b - a }));

// Sort method return the data output ` 89,34,12,4,3 `

Compare function return less than 0, sort `a` to an index lower than `b` then `a` comes first. If  Compare function returns 0 it will be unchanged but sort the other element. if Compare function is greater than 0, it will sort `b` to an index lower than `a`, `b` comes first.

Please let me know your feedback and suggestion.