2

I try to sort (by lodash orderBy) the array which describes the tree like this:

const users = [
  { name: '10', pos: '0-0-0' },
  { name: '20', pos: '0-0-1' },
  { name: '21', pos: '0-0-1-1' },
  { name: '40', pos: '0-0-11' },
  { name: '30', pos: '0-0-6' }
];

const sortedUsers = _.orderBy(users, [user => parseInt(user.pos.split("-").join("0"))], ['asc']);
console.log(sortedUsers);

it's not a good way because I have got the order:

'0-0-0', '0-0-1', '0-0-6', '0-0-11', '0-0-1-1'

but expected:

'0-0-0', '0-0-1', '0-0-1-1, '0-0-6', '0-0-11''

How to sort this array properly? Thanks!

PunKHS
  • 47
  • 5

1 Answers1

1

You could take String#localeCompare and use options for sorting the same column of the string.

const users = [{ name: '10', pos: '0-0-0' }, { name: '20', pos: '0-0-1' }, { name: '21', pos: '0-0-1-1' }, { name: '40', pos: '0-0-11' }, { name: '30', pos: '0-0-6' }];

users.sort((a, b) => a.pos.localeCompare(b.pos, undefined, { numeric: true, sensitivity: 'base' }));

console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392