How to use sort() Method In Javascript
This is also very simple method but it is not optimised approach. In this method, we sort the array by using the JavaScript sort() inbuilt method and then compares with the original array that both array are equal or not. If they are equal, then array is sorted.
Example:
function checkSorted(arr) {
const sortArr = [...arr].sort((a, b) => a - b);
return JSON.stringify(arr) === JSON.stringify(sortArr);
}
// Example usage
const arr1 = [32, 39, 48, 56];
const arr2 = [22, 65, 1, 39];
console.log(checkSorted(arr1));
console.log(checkSorted(arr2));
Output
true false
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
JavaScript Program to Check an Array is Sorted or Not
In this article, we will learn how to check if the array is sorted in JavaScript. JavaScript Array is a single variable that is used to store elements of different data types. Now, we have to find whether the array is sorted or not.
Examples:
Input : const arr = [1, 2, 3, 4, 5];
Output : true
Input : const arr = [3, 1, 4, 2, 5];
Output : false
Below are the following approaches through which we can check if the array is sorted or not:
Table of Content
- Using the Brute Force Approach
- Using the every() Method
- Using sort() Method
- Using Recursion
- Using Array.reduce()