A function to split an string of alphabets and numbers into arrays and sort them respectively 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 &amp;&amp; lastCharIsNumber)  lastArray.push(char)
        else if (!currentCharIsNumber &amp;&amp; !lastCharIsNumber) lastArray.push(char)
        else tempArray.push([char])
      }
    
      tempArray.forEach(item =&gt; item.sort())
    
      return tempArray.map(array =&gt; array.join('')).join('')
    }
    
    console.log(fn1(string1) === string2); // true




Can anyone help to improve my solution?
You can use RegEx to extract the sequence of alphabets or numbers.
To match alphabets/number, use character class in Regular expression as below

/[A-Z]+|[0-9]+/


to match all occurrences, use g(global) flag.

After extracting sequences, use Array#reduce with Array#sort &amp; Array#join to get the sorted string.



const str1 = 'AYUKB17053UI903TBC';
const str2 = 'ABKUY01357IU039BCT';

console.log(str1
  .match(/[A-Z]+|[0-9]+/g)
  .reduce((a, c) =&gt; a + [...c].sort().join(''), '')
    === str2
);