Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,637 questions

55,372 answers

573 users

How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in JavaScript

1 Answer

0 votes
/*
    We want to sort characters in this strict order:
    1. lowercase letters   (a–z)
    2. uppercase letters   (A–Z)
    3. odd digits          (1,3,5,7,9)
    4. even digits         (0,2,4,6,8)

    Strategy:
    ---------
    Assign each character a "category rank" and sort by:
        (category rank, natural character order)

    JavaScript's Array.sort() with a custom comparator
    is the idiomatic and efficient way to do this.
*/

/// Returns category rank for sorting.
/// Lower rank = comes earlier.
function category(c) {
    if (c >= "a" && c <= "z") return 0;   // lowercase
    if (c >= "A" && c <= "Z") return 1;   // uppercase

    if (c >= "0" && c <= "9") {
        const d = c.charCodeAt(0) - "0".charCodeAt(0);
        return (d % 2 === 1) ? 2 : 3;     // odd digits → 2, even digits → 3
    }

    return 4; // fallback (should not happen for alphanumeric input)
}

/// Custom comparator for sorting characters
function compareChars(a, b) {
    const ca = category(a);
    const cb = category(b);

    if (ca !== cb)
        return ca - cb;   // sort by category first

    return a.localeCompare(b);  // tie-breaker: natural order
}

function sortAlphaNumeric(s) {
    // Convert string to array of characters
    const arr = [...s];

    // Sort using custom comparator
    arr.sort(compareChars);

    // Rebuild sorted string
    return arr.join('');
}

// Usage
const s = "a2B3cD8f1Z0";
const result = sortAlphaNumeric(s);
console.log("Sorted result:", result);


/*
run:

Sorted result: acfBDZ13028

*/

 



answered Jul 14 by avibootz

Related questions

...