Arranging lexicographically and removing whitespaces in JavaScript

We need to write a JavaScript function that takes a string containing alphabets and whitespaces, then returns a new string with characters arranged in case-insensitive alphabetical order while removing whitespace and punctuation.

Problem Statement

Our function should iterate over the input string and concatenate characters into a new string following "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation are simply removed.

For example:

Input:

const str = 'some simple letter combination!';

Expected Output:

abceeeeiiillmmmnnoooprssttt

Solution Using Nested Loops

The approach uses nested loops to iterate through each letter of the alphabet (a-z) and then search for matching characters in the input string:

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));
abceeeeiiillmmmnnoooprssttt

How It Works

The function works by:

  • Outer loop iterates through ASCII codes 97-122 (a-z)
  • Inner loop searches the input string for characters matching the current letter
  • When a match is found, the original character (preserving case) is added to the result
  • Non-alphabetic characters are automatically ignored

Alternative Solution Using Array Methods

Here's a more modern approach using array methods:

const str = 'some simple letter combination!';
const orderStringModern = (str = '') => {
    return str
        .split('')
        .filter(char => /[a-zA-Z]/.test(char))
        .sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase()))
        .join('');
};
console.log(orderStringModern(str));
abceeeeiiillmmmnnoooprssttt

Comparison

Method Time Complexity Readability Performance
Nested Loops O(26 * n) Lower Better for large strings
Array Methods O(n log n) Higher Simpler implementation

Conclusion

Both solutions effectively arrange characters alphabetically while removing non-alphabetic characters. The nested loop approach offers predictable performance, while the array method approach provides cleaner, more readable code.

Updated on: 2026-03-15T23:19:00+05:30

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements