I am currently working on a Codewars challenge, http://www.codewars.com/kata/your-order-please. The task is to take a string and re-order the words according to a value found in each word of the string, for example:"is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est".
I have written a solution that successfully passes all tests provided and returns the correct string. https://jsfiddle.net/louisstanard/5hygz6wb/
function order(words){
var ordered = [];
var arr = words.split(' ');
var n = 1;
while (n <= arr.length) {
for (var i = 0; i < arr.length; i++) {
var stringArr = arr[i].split('');
stringArr.forEach(function(currentValue, index) {
if (parseInt(currentValue) === n) {
ordered.push(arr[i]);
n++;
}
});
}
}
return ordered.join(' ');
}
My problem is that when I attempt to submit the solution I receive an error saying "Process was terminated. It took longer than 6000ms to complete". I chose to use a while loop because I want to continue iterating over each word in the string looking for a number until I've built up a new array whose length is the same as the original array.
I'm new to writing more performant JS, but I know that while loops (and probably a for nested inside of a while) can be very expensive operations. Does anyone have insight as to why this might be taking too long to run? Are there any glaring performance issues I'm not seeing? Or perhaps a better approach altogether? Thanks!