Here's another way that uses the order as a template which we fill through a reduce()
and remove the empties
let order = "SM,MD,2X,3X,4X,5X,LG,XL".split(","); // our example order
"3X,LG,XL,4X".split(',') // array-ify the input
.reduce((b,a) => {b[order.indexOf(a)]=a; return b}, // fill the available slot in the accumulator
[].fill('',0,order.length)) //... which was pre-populated with empty indexes from fill()
.filter(e=>e) //filter out the empties
and it fits nicely on one line
let sizes = "3X,LG,XL,4X".split(',').reduce((b,a) => {b[order.indexOf(a)]=a; return b},[].fill('',0,order.length)).filter(e=>e)
it uses reduce to fill an array of available sizes in the order of the example order
and then filters out the empties
let order = "SM,MD,2X,3X,4X,5X,LG,XL".split(",");
const sortSizes = (s) => {
return s.split(',').reduce((b,a) => {b[order.indexOf(a)]=a; return b},[].fill('',0,order.length)).filter(e=>e)
}
let input="3X,LG,XL,4X";
//Output: LG,XL,3X,4X
console.log(sortSizes(input));
input = "LG,XL,2X,5X,2X"
//Output: SM,MD,2X,2X,5X
console.log(sortSizes(input));