javascript
Parameters: array: Array
The function requires an array as an input parameter
Returns: This function returns the input array sorted in descending order
The 'sortArrayDesc' function in JavaScript showcases how to manipulate an array by returning a version sorted in descending order.
Hello fellow programmer, glad to have you here! We are about to embark on a journey through the inner workings of JavaScript. The task in hand is to code a function, particularly known as 'sortArrayDesc'. This function’s primary job is to sort an array in descending order. The guidelines given will assist you through the process in a detailed manner. Happy Coding!
The function sortArrayDesc
needs to sort an array in descending order. When an array of numbers is passed, the function should return a new array with the numbers sorted from the largest to the smallest.
For the purpose of this guide, we will use the JavaScript's built-in sort()
function, and a custom comparison function to sort the array in descending order.
function sortArrayDesc(array) {
}
sort()
functionThe sort()
function, sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to the string Unicode code points.
However, we need to specify a custom sorting function for the sort()
function to sort the numbers in descending order.
function sortArrayDesc(array) {
return array.sort();
}
sort()
functionWe need to assign a custom sorting function to the sort()
function as an argument. In our case, we need the function to sort numbers in descending order. We use b - a
to sort in descending order because sort()
function sorts in ascending order by default.
function sortArrayDesc(array) {
return array.sort(function(a, b) {
return b - a;
});
}
Now it's time to test our function. We will use an array of numbers and the function should return the same numbers of the array sorted in descending order.
console.log(sortArrayDesc([10, 5, 8, 1, 7])); // [10, 8, 7, 5, 1]
Here's the final implementation of the sortArrayDesc
function. This function takes an array of numbers as an argument and returns a new array of the same numbers sorted in descending order.
function sortArrayDesc(array) {
return array.sort(function(a, b) {
return b - a;
});
}
As you can see, the JavaScript's built-in sort()
function makes it easy to sort arrays in either ascending or descending order. You just need to pass a custom sorting function as an argument, depending on how you want to sort the array.
This function utilizes the mathematical principle of comparison. In a set of numbers, there is a relationship where any two numbers can be compared to one another. The 'sortArrayDesc' function iterates over each pair of elements in the array, comparing them and switching their positions if necessary.
Learn more