I'm trying to sort an array of string that sometimes contain numbers.
Here are examples of the array potentially received and the expected result:
- ["12W", "60W", "25W"] -> ["12W","25W","60W"]
- ["IP67", "IP68", "IP20"] -> ["IP20","IP67","IP68"]
- ["White", "Red", "Black"] -> ["Black", "Red", "White"]
- ["100cm", "10cm", "50cm"] -> ["10cm","50cm","100cm"]
- ["3000°K", "2700°K", "2000°K"] -> ["2000°K","2700°K","3000°K"]
Here's my actual code: all_values is the array i have to sort.
const customSort = (a, b) => {
return (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g[0])))
;};
const hasNumber = (myString) => {
return /\d/.test(myString);};
// Sort filters
this.product.product_filter.map(filter => {
if (hasNumber) {
filter.all_values = filter.all_values.sort(customSort);
} else {
filter.all_values = filter.all_values.sort();}
});
Thanks in advance for your help.