Arranging lexicographically and removing whitespaces in JavaScript


Problem

We are required to write a JavaScript function that takes in a string, str, that contains alphabets and whitespaces

Our function should iterate over the input string and perform actions so that the characters are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!

For example, if the input to the function is −

Input

const str = 'some simple letter combination!';

Output

const output = 'abceeeeiiillmmmnnoooprssttt';

Example

Following is the code −

 Live Demo

const str = 'some simple letter combination!';
const orderString = (str = '') => {
   let res = '';
      for(let i = 97; i < 123; ++i){
         for(let j = 0; j < str.length; j++){
            if(str[j].toLowerCase().charCodeAt() === i){
               res += str[j];
            };
         };
      };
   return res;
};
console.log(orderString(str));

Output

abceeeeiiillmmmnnoooprssttt

Updated on: 22-Apr-2021

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements