Reputation: 3774
How do I sort an array of objects alphabetically in Typescript. I have array in this format now -
I am looking to sort it alphabetically by the channel field.
Here is what I tried which I got from the web.It didn't show any errors and also it didn't produce the expected result as well.
this.currentPickSelection = this.currentPickSelection.sort((a, b) => {
if (a.channel > b.channel) {
return 1;
}
if (a.channel < b.channel) {
return -1;
}
return 0;
Upvotes: 0
Views: 7352
Reputation: 5633
You basically have to sort an array of objects.
Change your JSON object as an array of objects.
[
{
"pickCode":"",
"cbsCode": "",
"channel": "",
"logo": "",
"tag": ""
},
{
"pickCode":"",
"cbsCode": "",
"channel": "",
"logo": "",
"tag": ""
},
{
"pickCode":"",
"cbsCode": "",
"channel": "",
"logo": "",
"tag": ""
}
]
Write a reusable function like this. (Same logic you've used. I've added the toLowerCase()
part)
private compare(a, b) {
if (a.channel.toLowerCase() < b.channel.toLowerCase()) {
return -1;
}
if (a.channel.toLowerCase() > b.channel.toLowerCase()) {
return 1;
}
return 0;
}
And then, let's assume that arrayOfObjects variable name is channelDetails
,
simply this.channelDetails.sort(this.compare);
would do this.
Upvotes: 0
Reputation: 22534
You have a multidimensional array. Your array#sort
method should be
this.currentPickSelection.sort((a, b) => a[0].channel.localeCompare(b[0].channel))
Upvotes: 6