Check If an Array is Ascending, Descending, or Not Sorted in JavaScript



We are required to write a JavaScript function that takes in an array of Numbers. The function should check whether the numbers in the array are in increasing order, or in decreasing order or in no specific order.

If the array contains only one element then we should return a message saying not enough elements.

And if the array has all the elements equal, we should return a message saying all elements are equal.

Example

The code for this will be −

const arr1 = [7, 2, 1, 3, 2, 1];
const arr2 = [1, 1, 2, 3, 7, 7];
const determineOrder = arr => {
   if(arr.length < 2){
      return 'not enough items';
   };
   let ascending = null;
   let nextArr = arr.slice(1);
   for(var i = 0; i < nextArr.length; i++) {
      if(nextArr[i] === arr[i]){
         continue;
      }else if(ascending === null) {
         ascending = nextArr[i] > arr[i];
      }else if (ascending !== nextArr[i] > arr[i]){
         return 'unsorted';
      };
   }
   if(ascending === null){
      return 'all items are equal';
   };
   return ascending ? 'ascending' : 'descending';
};
console.log(determineOrder(arr1));
console.log(determineOrder(arr2));
console.log(determineOrder([1, 1, 1, 1]));
console.log(determineOrder([7, 2, 2, 1]));

Output

The output in the console −

unsorted
ascending
all items are equal
descending
Updated on: 2020-10-10T07:57:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements