settingsAccountsettings
Menusettings

Q: Usernames - JavaScript task

+2 votes

You are tasked to create a catalogue of usernames. The usernames will be strings that may contain any ASCII character. You need to order them by their length, in ascending order, as first criteria, and by alphabetical order as second criteria.

The input comes as array of strings. Each element represents a username. Sometimes the input may contain duplicate usernames. Make it so that there are NO duplicates in the output.

Examples:

Input:
Ashton
Kutcher
Ariel
Lilly
Keyden
Aizen
Billy
Braston

Output:
Aizen
Ariel
Billy
Lilly
Ashton
Keyden
Braston
Kutcher


Input:
Denise
Ignatius
Iris
Isacc
Indie
Dean
Donatello
Enfuego
Benjamin
Biser
Bounty
Renard
Rot

Output:
Rot
Dean
Iris
Biser
Indie
Isacc
Bounty
Denise
Renard
Enfuego
Benjamin
Ignatius
Donatello


The output is all of the usernames, ordered exactly as specified above – each printed on a new line.

asked in JavaScript category by user samfred5830

1 Answer

+1 vote

Here is my answer:

function usernames(array) {
    let names = new Set();
    for (let arr of array) {
        names.add(arr);
    }

    console.log([...names].sort(sortAlphabeticaly).join('\n'));
    function sortAlphabeticaly(a, b) {
        let firstCriteria = a.length - b.length;
        if (firstCriteria !== 0) {
            return firstCriteria;
        } else {
            return a.localeCompare(b);
        }
    }
}

usernames([
    'Ashton',
    'Kutcher',
    'Ariel',
    'Lilly',
    'Keyden',
    'Aizen',
    'Billy',
    'Braston'
]);

 

answered by user ak47seo
...