I want to sort an array of clothing sizes based on an predefined order of regular expressions.
The expressions array looks like this:
const sizeOrder = [
/One Size/,
/[X/S]+S/i,
/^S$/i,
/^M$/i,
/^L$/i,
/[X]+L/i,
/[4-9]XL/i,
/[0-9,]+/,
];
What would be a neat and efficient way to sort an array, that would for example look like this:
const sizes = [
'45,5',
'S',
'XXS',
'XXL',
'XS',
'4XL',
'One Size',
'0',
'32',
'42,5',
'18',
'XXS/XS',
'XXXS',
'L'
];
As a first step I would create buckets for the corresponding regular expressions and if a match exists I push that value to the bucket, like so:
function exampleSort() {
const bucket = Array.from(new Array(sizeOrder.length), () => []);
sizes.forEach(size => {
const i = sizeOrder.findIndex(order => order.test(size));
if (i > -1) {
bucket[i].push(size);
}
});
}
After that I'd go through each bucket and sort them accordingly and then join those arrays together to one.
But I have two questions:
What about the special case of XXS/XS? How would I sort that bucket so that XXS/XS would be between XXS and XS?
This seems to be an imperative and naive implementation. Is there any other way to do this more efficiently?
This is my expected output:
const sorted = [
'One Size',
'XXXS',
'XXS',
'XXS/XS',
'XS',
'S',
'L',
'XXL',
'4XL',
'0',
'18',
'32',
'42,5',
'45,5'
];