JavaScript - Check if array is sorted (irrespective of the order of sorting)

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals and checks if the array is sorted or not (irrespective of the order of sorting.)

Our function should return true if the array is sorted, false otherwise. Following is the code −

Example

const arr = [1, 3, 56, 87, 99, 102, 144, 255, 456, 788, 999];
const isSorted = arr => {
   const { length: l } = arr;
   if(l <= 1){
      return true;
   };
   for(let i = 1; i < l; i++){
      const con1 = arr[i] > 0 && arr[i-1] < 0;
      const con2 = arr[i] < 0 && arr[i-1] > 0;
      if(con1 || con2){
         return false;
      };
   };
   return true;
};
console.log(isSorted(arr));

Output

Following is the output in the console −

true
raja
Published on 15-Sep-2020 11:45:15
Advertisements