Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array of objects alphabetically except for numbers?

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?

like image 372
Berg_Durden Avatar asked Jan 25 '23 17:01

Berg_Durden


1 Answers

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);
like image 149
Nina Scholz Avatar answered Jan 29 '23 12:01

Nina Scholz