I am trying to sort an array of objects by the name field but the ordering is wrong.
The order I am getting is [1, 10, 11, 2, 20, 21, 3]
Instead of [1, 2, 3, .... 10, 11, 20, 21]
It is sorting but putting 10 ahead of 2
Here is the code I am currently using.
const arr = [
{
"name": "Action 10",
"color": "transparent",
"type": "components"
},
{
"name": "Action 11",
"color": "transparent",
"type": "components"
},
{
"name": "Action 2",
"color": "transparent",
"type": "components"
},
{
"name": "Action 20",
"color": "transparent",
"type": "components"
},
{
"name": "Action 21",
"color": "transparent",
"type": "components"
},
{
"name": "Action 3",
"color": "transparent",
"type": "components"
},
{
"name": "Action 4",
"color": "transparent",
"type": "components"
},
{
"name": "Action 5",
"color": "transparent",
"type": "components"
},
{
"name": "Action 6",
"color": "transparent",
"type": "components"
},
{
"name": "Action 1",
"color": "transparent",
"type": "components"
}
]
function sorter(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
console.log(arr.sort(sorter));
'Action'as in"Action 1"and a sole digit sequence part like'21'as in"Action 21"the regex based solutions which are just after matching digits via/\d+/and parsing and sorting it are equal. But any of these approaches fail already for a lowercase"action 10"versus the original"Action 10"and of cause for any word other than'Action'within an item'snameproperty.