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

0 votes
24 views
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

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

1 Answer

0 votes
Ethan Karla answered 11 days ago by Ethan Karla
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);