How to use the every() Method In Javascript
This is also a kind of iterative method but in this approach we use every() Method for iteration instead of for loop. JavaScript has many inbuilt methods. The Javascript Array.every() method considers all the elements of an array and then further checks whether all the elements of the array satisfy the given condition (passed by in user) or not that is provided by a method passed to it as the argument.
Example:
function checkSorted(arr) {
return arr.every((value, index, array) =>
index === 0 || value >= array[index - 1]);
}
// 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(1)
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()