How to sort array of object alphabetically in lwc salesforce.

  • Post author:
  • Post category:Blog
  • Post comments:0 Comments

Here we will give you simplest way to sort of array of object in lightning web component . Suppose that you have a data in key & value format , and you want to sort that data in alphabetical order like A-Z , then you are on the right place , here we will you solution for that.

Here is sample data before sort

 @track arrayOfObjectsBeforeSoft =[
        {"value":"J","label":"J"},{"value":"A","label":"A"},
        {"value":"D","label":"D"},{"value":"P","label":"P"},
        {"value":"B","label":"B"},{"value":"C","label":"C"},
 ];

Use the following code to sort your above array

@track arrayOfObjectsAfterSort = this.arrayOfObjectsBeforeSoft.sort((a,b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0));

These code will return the following result

[
{"value":"A","label":"A"},{"value":"B","label":"B"},
{"value":"C","label":"C"},{"value":"D","label":"D"},
{"value":"J","label":"J"},{"value":"P","label":"P"}
]

These is how to sort array of object alphabetically.

Leave a Reply