This post will discuss how to determine whether an integer array is sorted in JavaScript.

There are several ways to check whether an array is sorted in JavaScript. Here are some of the possible functions, along with some examples:

1. Using Array.every() function

The Array.every() function tests whether all elements in the array pass a test implemented by a provided function. We can use this function to check whether each element in the array is greater than or equal to the previous element, for ascending order, or less than or equal to the previous element, for descending order. Here’s an example:

Download  Run Code

 
This function returns true if every element in the array is greater than or equal to the previous element, or if it is the first element. To check if the array is descending, we can simply flip the comparison operator to <=.

Download  Run Code

2. Using Lodash or Underscore Library

Another way is to use a library like Lodash or Underscore that provides a function to check if an array is sorted. We can use the _.every() function to check if every element is in order as follows:

Download Code

3. Using a loop

One way is to use a loop to iterate over the array and compares each element with the next element, using a flag variable to indicate whether the array is sorted or not. We can use a different comparison operator for ascending or descending order. Here’s an example:

Download  Run Code

4. Using a custom function

Another way is to define a custom function that can check whether an array is sorted by comparing the last two elements of the array, and then recursively calling itself on the subarray that excludes the last element. We can use a different comparison operator for ascending or descending order. Here’s an example:

Download  Run Code

That’s all about determining whether an integer array is sorted in JavaScript.