I'm currently working on unscrambling an array. The array contains string elements that are not in the correct order, with numbers attached to indicate their desired position. My goal is to extract these numbers from each item and rearrange them in a new array based on those numbers. For instance, let's take
var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"]
. I already have a function that can locate and isolate these numbers within each item.
function unscramblePhrase() {
var scrambled = ["pizza4", "to2", "I0", "eat3", "want1"];
var unscrambled = [];
for (var counter = 0; counter < scrambled.length; counter++) {
numPosition = scrambled[counter].search('[0-9]');
arrayIndex = scrambled[counter].substring(numPosition);
console.log(arrayIndex);
unscrambled.push(scrambled[arrayIndex]);
}
console.log(unscrambled)
}
Currently, my approach of using the extracted numbers to reposition the elements in a new array is not yielding the desired outcome - instead of unscrambling, it just produces another scrambled array:
["want1", "I0", "pizza4", "eat3", "to2"]
.