What is the role of Array.sort() in JS?

Asked 19-Jul-2021
Viewed 153 times

1 Answer


1

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings.
Syntax
// Functionless

sort()
// Arrow function
sort((firstEl, secondEl) => { ... } )
// Compare function
sort(compareFn)
// Inline compare function
sort(function compareFn(firstEl, secondEl) { ... })
Example:
const fruits = ['BANANA','APLLE','orang','grapes','mango'];

    fruits.sort();
    console.log(fruits);
    // expected output: Array ['Dec', 'Feb', 'Jan', 'March']
const array1 = [54,21,32,5,1,21];
const array= array1.sort(function(a,b){
    return a-b;
});
    console.log(array);