2

I want to sort by property name in array object.

const arr = [
  {id:1, name: 'A1'},
  {id:2, name: 'A2'},
  {id:3, name: 'A3'},
  {id:4, name: 'B1'},
  {id:5, name: 'B2'},
  {id:6, name: 'A21'},
  {id:7, name: 'A11'},
  {id:8, name: 'A4'},
  {id:9, name: 'A12'},
]

arr.sort((a,b) => a.name.localeCompare(
  b.name,
  undefined,
  { numeric: true }
))

console.log(arr)

The result I am looking for is 1:A1, 2:A2, 3:A3, 7:A11, 6:A21, 4:B1, 5:B2.

Thank you :)

Nawapol R.
  • 57
  • 9
  • Does this answer your question? [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – SMAKSS Oct 25 '22 at 11:47
  • You'd have to separate the two pieces of data (the letter and the number), parse the numeric string as a number, and sort on the two properties separately. – David Oct 25 '22 at 11:48

2 Answers2

1

Use localeCompare with numeric: true:

arr.sort((a, b) => a.name.localeCompare(
    b.name,
    undefined,
    { numeric: true }
));
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
-1

You can use .localeCompare with numeric option

DEMO:

const arr = [{id:1, name: 'A1'},{id:2, name: 'A2'},{id:3, name: 'A3'},{id:4, name: 'B1'},{id:5, name: 'B2'},{id:6, name: 'A21'},{id:7, name: 'A11'}];

const sorted = arr.sort(({ name: a }, { name: b }) => 
    a.localeCompare(b, undefined, { numeric: true }));
    
console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0 }
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48