Which array method sorts the elements of an array?

Understanding the Array sort() Method in JavaScript

The correct answer to the question "Which array method sorts the elements of an array?" is sort(). This method is a built-in function of JavaScript used to sort the elements of an array.

Here's a quick example of how it works:

let fruit = ['banana', 'apple', 'cherry', 'date'];
fruit.sort(); // this will output: ['apple', 'banana', 'cherry', 'date']

In the example above, the sort() method sorts the element of the fruit array in alphabetical order.

In JavaScript, when sort() is used without a compare function, it converts the elements into strings and sorts them in lexicographical (dictionary or alphabetical) order. If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

To correctly sort numbers, you can pass a compare function as an argument to the sort() method:

let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort(function(a, b){return a - b});
//this will output: [1, 5, 10, 25, 40, 100]

Here, the sort() method sorts the numbers array in ascending order based on the return value of the compare function. A subtraction a - b returns a value less than, equal to, or greater than zero. If the result is less than zero, a is sorted to an index lower than b. This means a comes first.

To sort in descending order, the compare function should return b - a:

let numbers = [40, 100, 1, 5, 25, 10];
numbers.sort(function(a, b){return b - a});
//this will output: [100, 40, 25, 10, 5, 1]

The sort() method is a powerful tool when working with arrays in JavaScript. It's quite versatile, as you can specify your own sorting order rules by passing a comparison function to the sort(). But remember, it sorts the array in place, meaning it modifies the original array. So, if you don't want the original array to be changed, you should make a copy before sorting.

Do you find this helpful?