Order based on the number present in the text

Question

this is my first time using this site. I am working on a code, which I am trying to solve. I am unable to get the output as required. This is about sorting arrays. I know that I should be using array.sort(), but I have to use a custom code to sort them because, the string I have is:

is2 Thi1s T4est 3a

And I am converting this string into array using array = str.split(" ") and the challenge in this is, I need to find the number in it. So what I am trying to do really is, getting the number using:

parseInt(array[i]);

It works only once or twice. For e.g., for the above string, it gives me:

parseInt(array[0]);  // NaN
parseInt(array[1]);  // NaN
parseInt(array[2]);  // NaN
parseInt(array[3]);  // 3

I am not sure how I could reliably take the number from the string. Should I use RegEx or something for this?


Show source
| javascript   | sorting   | arrays   | string   2017-01-06 23:01 4 Answers

Answers to Order based on the number present in the text ( 4 )

  1. 2017-01-06 23:01

    parseInt() will only parse a number at the beginning of the string, not in the middle. Use a regexp to find the number. This will find the first number anywhere in the string:

    var match = str.match(/\d+/);
    var number = match ? parseInt(match[0]) : 0;
    
  2. 2017-01-06 23:01

    Instead of split you could use match to get the words in an array, but only the word parts that start with a digit.

    In a second step you can then do the parseInt or in one go with map(parseFloat):

    var str = 'is2 Thi1s T4est 3a';
    var array = str.match(/\d\S*/g);
    console.log(array);
    array = array.map(parseFloat);
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

  3. 2017-01-06 23:01

    I really appreciate for giving such a detailed explanation. The first issue is using parseInt() will not work, if the number is hidden inside after the first character. So to get the number from the text, please replace your parseInt() code with the following:

    array[i].match(/(\d+)/)[0]
    

    This is a Regular Expression, which reads the string and gets the matching number from the array.

    array[0].match(/(\d+)/)[0]  // 2
    array[1].match(/(\d+)/)[0]  // 1
    array[2].match(/(\d+)/)[0]  // 4
    array[3].match(/(\d+)/)[0]  // 3
    

    Now since you need to order them based on the numbers, you can do this way. You need to put them in the right order based on the numbers, let's have a final array defined this way:

    var finalArray = [];
    

    We need to start filling each of the entries with the right index, based on the value that you received from the array. i.e.:

    finalArray[0] = "Thi1s";
    finalArray[1] = "is2";
    finalArray[2] = "3a";
    finalArray[3] = "T4est";
    

    To make this, we can either loop or use a forEach() function. I love to use a map function, but it's heavier than forEach, while many prefer loop. So, the function looks like this:

    array.forEach(function (value) {
      // Value here is the current value. Could be Thi1s or something.
      finalArray[parseInt(array[i].match(/(\d+)/)[0])] = value;
    });
    

    Now that we have filled in the finalArray, it's time to join them and send it as return value.

    return finalArray.join(" "); // Join each with a space.
    

    The complete code will be looking like:

    function getSortedValues(str) {
      var finalArray = [];
      str.split(" ").forEach(function (v) {
        if (!!v)
          finalArray[parseInt(v.match(/(\d+)/)[0])] = v;
      });
      return finalArray.join(" ").trim();
    }
    
    console.log(getSortedValues("is2 Thi1s T4est 3a"));

  4. 2017-01-06 23:01

    This is about sorting arrays.

    The solution using String.prototype.match(), Array.prototype.sort() and String.prototype.localeCompare()(with numeric collation) functions:

    var s = 'is2 Thi1s T4est 3a',
        words = s.split(' ');
    
    words.sort(function(a,b){
      return a.match(/\d+/)[0].localeCompare(b.match(/\d+/)[0], 'kn');
    });
    
    console.log(words.join(' '));

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare


    The alternative sorting approach would be:

    ...
    words.sort(function(a,b){
        return a.match(/\d+/)[0] - b.match(/\d+/)[0];
    });
    

Leave a reply to - Order based on the number present in the text

◀ Go back