Check if An Array is Sorted | JavaScript


Check If An Array is Sorted using JavaScript

Logic : You can take the first item and second item and subtract the value. If second item minus the first item is positive, they are sorted. Now you can can move the index forward and check the next two and similarly.

Here is the JavaScript implementation to check is an Array is sorted.

function sorted(arr){
    let second_index;
	for(let first_index = 0; first_index < arr.length; first_index++){
  	  second_index = first_index + 1;
      if(arr[second_index] - arr[first_index] < 0) return false;
    }
    return true;
}

let arr = [1,2,3,4];
console.log('is array sorted ? ' + sorted(arr));
// is array sorted ? true