How do I check if an array is sorted in ascending or descending order in JavaScript?
Antek N
To check if an array is sorted in ascending or descending order in JavaScript, you can use a simple loop or a combination of array methods. Here are two commonly used approaches:
1. Using a loop:
You can iterate over the array and compare each pair of adjacent elements to determine the ordering. Here's an example:
In this example, theisAscending function checks if the array is sorted in ascending order by comparing each element with the previous one. If any element is smaller than its predecessor, the function returnsfalse. Similarly, theisDescending function checks if the array is sorted in descending order by comparing each element with the previous one. If any element is greater than its predecessor, the function returnsfalse.
2. Using array methods:
Alternatively, you can leverage array methods such asevery() orreduce() to check the ordering. Here's an example usingevery():
In this example, theevery() method is used to iterate over the array and check if each element satisfies a specific condition. The condition compares each element with its predecessor to ensure that the array is sorted either in ascending or descending order.
Both approaches provide a way to determine if an array is sorted in ascending or descending order. Choose the one that best suits your coding style and requirements.