Was it helpful?

Question

Check if an array is descending, ascending or not sorted in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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
raja
Published on 10-Oct-2020 11:27:23
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top