0

How do I sort an array of objects alphabetically in Typescript. I have array in this format now - enter image description here 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;
6
  • your json object is wrong Commented Jan 20, 2018 at 7:03
  • 1
    Why each array has an array again inside? You've to change the JSON object. Commented Jan 20, 2018 at 7:06
  • Possible duplicate of Sort array by firstname (alphabetically) in Javascript Commented Jan 20, 2018 at 7:07
  • @Saiyaff, I am trying to do that, But I am not sure how it happens. Commented Jan 20, 2018 at 7:14
  • @Tsvetan Ganev Thats the link I got that code snippet from. I was not able to solve with that posting, thats why I created another one. Commented Jan 20, 2018 at 7:15

2 Answers 2

6

You have a multidimensional array. Your array#sort method should be

this.currentPickSelection.sort((a, b) => a[0].channel.localeCompare(b[0].channel))
Sign up to request clarification or add additional context in comments.

1 Comment

That Worked. Thanks @Saiyaff Farouk
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.