sort() array method in javascript

parameter callback function example

Array methods were introduced in javascript in ES5. Before this, every array iteration was performed by loops. But after the introduction of array methods to perform array operations, work on an array has become very easy without the implementation of extra coding.

Here we will discuss some array methods.

why use sort()?

This method is used to sort elements of the array. sort() method converts all elements of the array into strings and then sorts them according to the unit code value of UTF-16. It does not create any new array. By default, arrays are sorted in ascending order.

syntax

//without any parameter

array.sort();

//compare Function method

array.sort(compareFn);

// arrow Function method

array.sort(a,b)=>{function body});

//Inline compare Function method

array.sort(function compareFn(){Function body});

Parameters

compareFunc

This function defines compare method by code.

a,b

The first and second parameters of the comparison function.

Return Value

It does not create a new array. It sorted the original array by swapping the values in the same array. The comparison function takes two parameters and returns three possible values 0, 1 and -1.

return value (compareFn(a,b)

sort(a,b)

>0

Sort b before a

<0

Sort a before b

===0

Keep the original order of a and b

Examples

Here, we will sort a name list.

Output:

Here again, we will sort numbers.

Output

Did you find this article valuable?

Support WebIndia by becoming a sponsor. Any amount is appreciated!