# Check if a numeric array is sorted in JavaScript

Sometimes, it's useful to know if an array is sorted in ascending or descending order. This can be especially useful in combination with other algorithms, such as binary search or sorting algorithms.

Sorting the whole array and comparing it to itself is the naive method, yet it's wildly inefficient. The more efficient way is the traditional `for` loop and some early returns.

Starting with the first two elements, calculate the `direction` of the array. If the `direction` changes at any point, return `0`. If the array is empty or has only one element, return `0`. If the `direction` remains the same for the whole array, return the `Math.sign()` of the `direction` to get `-1` for descending order and `1` for ascending order.

```const isSorted = arr => {
if (arr.length <= 1) return 0;
const direction = arr[1] - arr[0];
for (let i = 2; i < arr.length; i++) {
if ((arr[i] - arr[i - 1]) * direction < 0) return 0;
}
return Math.sign(direction);
};

isSorted([0, 1, 2, 2]); // 1
isSorted([4, 3, 2]); // -1
isSorted([4, 3, 5]); // 0
isSorted([4]); // 0```

## More like this

• JavaScript ·

### How can I check if an array is a superset of another array in JavaScript?

Check if an iterable is a superset of another one, excluding duplicate values.

• JavaScript ·

### How can I find the insertion index of an element in a sorted JavaScript array?

Given a sorted array, find the correct index to insert a given value.

• JavaScript ·

### Check if a JavaScript array includes any or all values in another array

Check if any or all the elements in an array are included in another array.

• JavaScript ·

### Initialize a JavaScript array with a given numeric range

Learn how to create an inclusive array with numbers in a range, using a common `step` difference.

Start typing a keyphrase to see matching snippets.