- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript - Check if array is sorted (irrespective of the order of sorting)
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
- Related Articles
- Large to Small Sorting Algorithm of already sorted array in JavaScript
- MongoDB query for documents matching array, irrespective of elements order
- Check if an array is descending, ascending or not sorted in JavaScript
- Sorting an associative array in ascending order - JavaScript
- Check if a string is sorted in JavaScript
- Identify all duplicates irrespective of the order of the input
- Check if items in an array are consecutive but WITHOUT SORTING in JavaScript
- Check if an array is sorted and rotated in Python
- Check if an array is sorted and rotated in C++
- Return a sorted array in lexicographical order in JavaScript
- Sorting one string by the order of second in JavaScript
- Uneven sorting of array in JavaScript
- Sorting digits of all the number of array - JavaScript
- Check if reversing a sub array make the array sorted in Python
- Alternative sorting of an array in JavaScript

Advertisements