skip to Main Content

I am trying this question from Codewars.

It requires me to to sort a string based on the number in each of the words.

Sighted as follows:
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

    Examples
    "is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
    "4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
    ""  -->  ""

I found this solution online.

    function order(words){
      
      return words.split(' ').sort(function(a,b){
        return a.match(/d/) - b.match(/d/);
      }).join(' ');
    }

I did not understand the second nested function with the regex, someone kindly explain to me how it works.

2

Answers


  1. To better understand the function, let’s just take it apart piece by piece:

    1. what means the regex /d/? -> this just means the digits 0 – 9.
    2. what means match(/d/) here? -> this returns the first digit in the given string
    3. why return a.match(/d/) - b.match(/d/)? -> because we want to sort the array of words by the numbers in the words ascending, we subtract the first from the second and returne the result.

    Summary:
    the second functions gets the first digit in a word, subtracts it from the following word and then sorts the the array ascending [1, 2, 3, 4, …] so the words get in the right order.

    Login or Signup to reply.
  2. let text = '4of Fo1r pe6ople g3ood th5e the2'
    let words = text.split(' ')
    console.log(words)
    // ["4of", "Fo1r", "pe6ople", "g3ood", "th5e", "the2"] 
    let a = words[0]
    console.log(a) // "4of"
    console.log(a.match(/d/)) // ["4"]
    
    // and the hack is that
    console.log(Number( ["4"] )) // it's 4 !!!
    // minus casts values to numbers:
    console.log(["4"] - ["1"]) // 3
    // which is used for sorting
    console.log('pe6ople'.match(/d/) - 'g3ood'.match(/d/)) // ["6"] - ["3"] = 3
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search