DEV Community

Hsabes
Hsabes

Posted on

Code challenge: Make it make sense

You're given a string that contains several words, each word interjected with a number. Your task is to write a function that sorts the words based on the numbers that are contained within them. The function should return the sorted words still containing their respective numbers.

Input:

"doi4ng y3ou 5today h1ow ar2e"

Output:

h1ow ar2e y3ou doi4ng 5today

Solution:

This is one of my favorite problem because you can use an iterating and sorting technique I find very fun. The first step is to convert our string into something we can work with by splitting it into an array.

function order(string){
  return wordsObj.split(" ")
}
Enter fullscreen mode Exit fullscreen mode

Output: ["doi4ng", "y3ou", "5today", "h1ow", "ar2e"]

The objective here is fairly simple, we need to sort the numbers from lowest to highest. How can we do that when they are in a string? Regex and iteration.

function order(words){
  return wordsObj = words.split(" ").map((element) => ({ num: element.replace(/[^0-9]+/g, ""), word: element}))
}
Enter fullscreen mode Exit fullscreen mode

We've mapped through our array and for each word we've created an object with a number and its associated word. Using regex, we can extract the letters from each element, leaving us with just the number. Since we want our final output to contain the number, we'll leave the word alone. This will return:

[
  { num: '2', word: 'is2' },
  { num: '1', word: 'Thi1s' },
  { num: '4', word: 'T4est' },
  { num: '3', word: '3a' }
]
Enter fullscreen mode Exit fullscreen mode

Now all that remains is sorting these objects by their number, and then extract out words.

function order(words){
  const wordsObj = words.split(" ").map((element, i) => ({ num: element.replace(/[^0-9]+/g, ""), word: element}))
  return wordsObj.sort((a, b) => a.num - b.num)
    .map((object) => object.word)
    .join(" ")
}
Enter fullscreen mode Exit fullscreen mode

Output: "Thi1s is2 3a T4est"

Clean refactor:

function order(words){
  return words.split(" ")
    .map((element, i) => ({ num: element.replace(/[^0-9]+/g, ""), word: element}))
    .sort((a, b) => a.num - b.num)
    .map((object) => object.word)
    .join(" ")
}
Enter fullscreen mode Exit fullscreen mode

Source

Top comments (0)