if I have a string AYUKB17053UI903TBC
. I want a function to return ABKUY01357IU039BCT
. So every alphabetical part of the string is sorted, as well as the numerical part. But they retain their original orders in the string...
We can assume that the input only contains number and English letters
I came up with a solution but I don't think it is elegant.
const string1 = 'AYUKB17053UI903TBC'
const string2 = `ABKUY01357IU039BCT`
function fn1(string1) {
let tempArray = [[]]
for (const char of string1) {
let lastCharIsNumber
let currentCharIsNumber
const lastArray = tempArray[tempArray.length - 1]
if(!lastArray.length){
lastArray.push(char)
continue
}
currentCharIsNumber = !Number.isNaN(Number(char))
lastCharIsNumber = !Number.isNaN(Number(lastArray[lastArray.length - 1]))
if (currentCharIsNumber && lastCharIsNumber) lastArray.push(char)
else if (!currentCharIsNumber && !lastCharIsNumber) lastArray.push(char)
else tempArray.push([char])
}
tempArray.forEach(item => item.sort())
return tempArray.map(array => array.join('')).join('')
}
console.log(fn1(string1) === string2); // true
Can anyone help to improve my solution?