0

I have a data which will show as the table and using orderBy(lodash) to sort data but it's not working as I want.

Now, I code as const data = orderBy(realData, ['name'], ['asc'])

Here's my data input: [{name: 'A1'},{name:'A2'},{name: 'A21'},{name:'B10'},{name: 'A100'},{name:'A22'},{name: 'B32'},{name:'A3'}]

The issue is 'orderBy' sort data as it text(ASCII sorting) current output: [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}]

but I would like the data output like this

[{name: 'A1'},{name:'A2'},{name:'A3'},{name: 'A21'},{name:'A22'},{name: 'A100'},{name:'B10'},{name: 'B32'}]

If anyone have any suggestion, please help.

Thank you.

ppppp
  • 199
  • 1
  • 2
  • 15
  • 1
    You might want to check out: https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings – Slawomir Chodnicki May 27 '19 at 10:32
  • Possible duplicate of [Javascript : natural sort of alphanumerical strings](https://stackoverflow.com/questions/2802341/javascript-natural-sort-of-alphanumerical-strings) – Ajit Panigrahi May 27 '19 at 11:06

2 Answers2

3

You can use string#localeCompare callback while sorting an array. To numerically sort the array use numeric property.

let data = [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}];
data.sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
console.log(data);
.as-console-wrapper {max-height: 100% !important; top: 0;}
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

An easy to understand way is like this:

data.sort((a, b) => {
  const listA = a.name.trim().split('');
  const listB = b.name.trim().split('');

  const categoryA = listA.splice(0, 1);
  const categoryB = listB.splice(0, 1);

  const numberA = listA.join('');
  const numberB = listB.join('');

  if (categoryA > categoryB) return 1;
  if (categoryA < categoryB) return -1;

  return numberA - numberB;
});
blastz
  • 525
  • 5
  • 14