0

I'm trying to order strings in an array depending on the number present in them, ie. 'h2ello f3ere b1ow' should return an array of ['b1ow', 'h2ello' ,' f3ere']. The following code works with two elements (h2ello and b1ow), but not when I add a third. Does anyone have an idea why this is?

function order(words){
  var sentence = [];
  words = words.split(" ");
 for (var i=0;i<words.length;i++){
   for (var m=0;m<words[i].length;m++){
    if (!isNaN(parseFloat(words[i][m])) && isFinite(words[i][m])){
     var idx = words[i][m];
         sentence.splice(idx, 0, words[i]);
     }
   }
 }
 console.log(sentence);
}

order('h2ello f3ere b1ow');

3 Answers 3

2

The easiest would be the direct sort of the array, without splicing to a place where the other places are unknown (in the loop).

This proposal uses Array#sort with a callback which looks for some decimal to sort for.

var array = 'h2ello f3ere b1ow'.split(' ');

array.sort(function (a, b) {
    return a.match(/\d+/) - b.match(/\d+/);
});

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

0

If you check documentation on splice: Array splice you will see that if index is longer than the length of the array, it will be set to the length of the array. So its just doing a push instead of setting at the index you want. One solution could be setting it manually:

sentence[idx-1] = words[i]

Depending on your needs you could also simplify your function quite a bit:

function order(words){
  words = words.split(" ").sort(function(a,b){
    return a.match(/\d/) -  b.match(/\d/) // get first digit and compare them
  })
 console.log(words);
}

Comments

0

I don't know which has better performance. BTW mine has one less regex match per comparison.

var sorted = 'h2ello f3ere b1ow'.split(' ')
  .map(w => ({ key: w.match(/\d+/)[0], word: w }))
  .sort((a, b) => a.key - b.key)
  .map(o => o.word).join(' ');

console.log(sorted);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.