Reputation: 159
Its simple like this. I need to sort an array with multiple values alphanumeric
this.tests = [
{
"title": "047 - Wunsc",
"link": "47",
},
{
"title": "014 - Expl",
"link": "14",
},
{
"title": "004 - Ausw",
"link": "4",
},
{
"title": "001 - Abhef",
"link": "1",
},
{
"title": "006 - Beurt",
"link": "6",
},
{
"title": "015 - Explo",
"link": "15",
},
{
"title": "029 - Physi",
"link": "29",
},
{
"title": "016 - Befra",
"link": "16",
}
]
This is what I've tried so far.
this.tests.sort(function (a, b) {
return parseFloat(a.title) - parseFloat(b.title);
});
this.tests.sort((a, b) => a.title.localeCompare(b.title));
But still getting no alphanumeric/natural sort
Upvotes: 0
Views: 89
Reputation: 386746
For this pattern just sort by string.
var data = [{ title: "047 - Wunsc", link: "47" }, { title: "014 - Expl", link: "14" }, { title: "004 - Ausw", link: "4" }, { title: "001 - Abhef", link: "1" }, { title: "006 - Beurt", link: "6" }, { title: "015 - Explo", link: "15" }, { title: "029 - Physi", link: "29" }, { title: "016 - Befra", link: "16" }];
data.sort((a, b) => a.title.localeCompare(b.title));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you like to sort only by description part, you could slice the string.
var data = [{ title: "047 - Wunsc", link: "47" }, { title: "014 - Expl", link: "14" }, { title: "004 - Ausw", link: "4" }, { title: "001 - Abhef", link: "1" }, { title: "006 - Beurt", link: "6" }, { title: "015 - Explo", link: "15" }, { title: "029 - Physi", link: "29" }, { title: "016 - Befra", link: "16" }];
data.sort((a, b) => a.title.slice(6).localeCompare(b.title.slice(6)));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1