![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements