Coding/Blog challenge 7

Coding/Blog challenge 7

This problem wasn't too hard for me, but I knew it would be easier if I learned some more RegEx. So, I took some time to watch some tutorials and to check out RegExr. I am glad that I decided to do this because the other way I thought of would be many more lines of code.

The Question

Yet another CodeWars challenge here.

JsProblem7.png

Immediately, I think how I could use the Array split method to split each word at the whitespace into an array where I can run a loop over each word to inspect it. I also set a variable with the regex I want to use. The regex expression "/[a-z|A-Z]/g" will return a number that will be included in the text of each word. It searches for a character from a to z in both lower case and uppercase letters & we do this globally to remove ALL the characters from a to z. Since there is only one number, 0-9 in each word, we don't need to worry about multiple numbers in each word.

//define our function
function order(words) {
    // set variable to regex
    numRegex = /[a-z|A-Z]/g;
    // split our words into singular words in an array
    words = words.split(' ');
}

After this, I decided to create a container array to hold my ordered words. I then use a higher order array object method forEach. For every word I have, I decide to replace the letter characters with an empty string, which leaves only the number. I set this to a variable for readability. Finally, we use this new variable to set where it should go in the container array. We also need to subtract by 1 since arrays start at 0 index, and we will never have a zero inserted into a word for this problem. Then we return our container array and use the join method to put the array back together as a string, adding the spaces.

function order(words) {
    numRegex = /[a-z|A-Z]/g;
    words = words.split(' ');
    //we create container array
    newWords = [];
    //and loop through all words
    words.forEach(word => {
        //now set index to the number contained within each word
        index = Number(word.replace(numRegex, ""))
        //then assign where the word should be according to its number
        newWords[index - 1] = word
    });
    //join container array together with spaces between words
    return newWords.join(" ");
}

BLAMO!

Hindsight

There is a lot more to learn for me with regex & I love looking at other solutions to the same problem because it gives me great ideas. Here's a clever solution I saw to this same problem.

var reg = /\d/;
function order(words){
  return words.split(' ').sort(comparator).join(' ');
}
function comparator(word, nextWord) {
  return +word.match(reg) - +nextWord.match(reg)
}

That's all folks!