I have this array:
sampleArray = [
{name: 'product-2'},
{name: 'product-15'},
{name: 'product-3'},
{name: 'product-10'}
]
I want to sort it using the property name
, alphabetically except for numbers inside the strings.
I am using sort
combined with localeCompare
:
sampleArray.sort((a, b) => a.name.localeCompare(b.name))
However, as name
is a string that contains a number I am getting this:
sampleArray = [
{name: 'product-10'},
{name: 'product-15'},
{name: 'product-2'},
{name: 'product-3'}
]
I need to get it in the correct order considering the numbers as well. What would be this:
sampleArray = [
{name: 'product-2'},
{name: 'product-3'},
{name: 'product-10'},
{name: 'product-15'}
]
I know if I was working only with numbers I could do that:
sampleArray.sort((a,b) => a - b)
But that's not the case.
How can I solve this?
You was half way, String#localeCompare
accepts an option where you can use a natural sorting with strings.
const
array = [{ name: 'product-2' }, { name: 'product-15' }, { name: 'product-3' }, { name: 'product-10' }];
array.sort((a, b) => a.name.localeCompare(
b.name,
undefined,
{ numeric: true, sensitivity: 'base' }
));
console.log(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With