 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a string is sorted in JavaScript
We are required to write a JavaScript function that takes in a string and checks whether it is sorted or not.
For example −
isSorted('adefgjmxz')  // true isSorted('zxmfdba')     // true isSorted('dsfdsfva')     // false Example
Following is the code −
const str = 'abdfhlmxz'; const findDiff = (a, b) => a.charCodeAt(0) - b.charCodeAt(0); const isStringSorted = (str = '') => {    if(str.length < 2){       return true;    };    let res = ''    for(let i = 0; i < str.length-1; i++){       if(findDiff(str[i+1], str[i]) > 0){          res += 'u';       }else if(findDiff(str[i+1], str[i]) < 0){          res += 'd';       };       if(res.indexOf('u') && res.includes('d')){          return false;       };    };    return true; }; console.log(isStringSorted(str));  Output
This will produce the following output in console −
true
Advertisements
 