This could also be done by just adding each sorted piece directly to a results array which then removes the need to use .flat()
at the end. One could also use:
result = result.concat(lastPiece.sort())
too, but I don't generally like the fact that .concat()
makes a whole new result array every time you call it (which seems less efficient to me if doing it a bunch of times) so that's why I used this:
result.push(...lastPiece.sort())
instead since you can add one array onto the other this way without making a whole new copy of the accumulated array every time (though it may be making a copy of lastPiece
each time). Since .flat()
could be implemented in native code, it may be plenty efficient (as used in the first implementation).
Anyway, here's an implementation that uses result.push(...lastPiece.sort());
to accumulate results as you go:
const string1 = 'AYUKB17053UI903TBC';
const string2 = 'ABKUY01357IU039BCT';
function sortPieces(str) {
const result = [];
let lastPiece = [];
let lastType;
for (const char of str) {
const nextType = (char >= "0" && char <= "9") ? "number" : "letter";
if (nextType === lastType || !lastType) {
// either same type as previous char or first char in string
lastPiece.push(char);
} else {
// different type of char than previous char, start a new piece
result.push(...lastPiece.sort());
lastPiece = [char];
}
lastType = nextType;
}
result.push(...lastPiece.sort());
return result.join("");
}
let result = sortPieces(string1)
console.log(result === string2, result);