How do I check if an array is sorted in ascending or descending order in JavaScript?
Antek N
antek n profile pic

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

function isAscending(array) {
  for (let i = 1; i < array.length; i++) {
    if (array[i] < array[i - 1]) {
      return false;
    }
  }
  return true;
}

function isDescending(array) {
  for (let i = 1; i < array.length; i++) {
    if (array[i] > array[i - 1]) {
      return false;
    }
  }
  return true;
}

const ascendingArray = [1, 2, 3, 4, 5];
const descendingArray = [5, 4, 3, 2, 1];

console.log(isAscending(ascendingArray)); // Output: true
console.log(isAscending(descendingArray)); // Output: false

console.log(isDescending(ascendingArray)); // Output: false
console.log(isDescending(descendingArray)); // Output: true

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():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

function isAscending(array) {
  return array.every((value, index, arr) => index === 0 || value >= arr[index - 1]);
}

function isDescending(array) {
  return array.every((value, index, arr) => index === 0 || value <= arr[index - 1]);
}

const ascendingArray = [1, 2, 3, 4, 5];
const descendingArray = [5, 4, 3, 2, 1];

console.log(isAscending(ascendingArray)); // Output: true
console.log(isAscending(descendingArray)); // Output: false

console.log(isDescending(ascendingArray)); // Output: false
console.log(isDescending(descendingArray)); // Output: true

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.