-1

This is my array

var a=[{name:'ABC125', sName: 'sadf'},{name:'ABC12', sName: 'sadf'},{name:'ABC15', sName: 'sadf'},{name:'Sbc125', sName: 'sadf'},{name:'pcb125', sName: 'sadf'}];

my Code for sort is

a.sort((x,y)=>(x.name.toLowerCase() > y.name.toLowerCase()) ? 1 : -1)

but this returns me as

enter image description here

Ele
  • 32,412
  • 7
  • 33
  • 72
Tejas
  • 197
  • 1
  • 10

2 Answers2

1
a.sort((x, y) => x.name.localeCompare(y.name, 'en', { numeric: true }))
Tigran Abrahamyan
  • 746
  • 1
  • 3
  • 7
  • How do you know the OP wants a sorting approach with numbers only? and more than that, you didn't even explain your answer. – Ele Aug 25 '20 at 14:08
  • Who is OP? Why explain when you can google the [localeCompare](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare) and find out what's going on here? – Tigran Abrahamyan Aug 25 '20 at 14:15
  • OP = Original poster - [how to answer](https://stackoverflow.com/help/how-to-answer) – Ele Aug 25 '20 at 14:18
0
var content=[
{name:'ABC125', sName: 'sadf'},
{name:'ABC12', sName: 'sadf'},
{name:'ABC15', sName: 'sadf'},
{name:'Sbc125', sName: 'sadf'},
{name:'pcb125', sName: 'sadf'}
];


content.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})



console.log(content)

output will be

(5) [{…}, {…}, {…}, {…}, {…}]
0: {name: "ABC125", sName: "sadf"}
1: {name: "ABC12", sName: "sadf"}
2: {name: "ABC15", sName: "sadf"}
3: {name: "Sbc125", sName: "sadf"}
4: {name: "pcb125", sName: "sadf"}

Credits to https://stackoverflow.com/a/51169/3046937

There is already answer exists here Javascript : natural sort of alphanumerical strings

Manjunath Siddappa
  • 2,100
  • 1
  • 18
  • 38