How to sort array of object alphabetically in lwc salesforce.

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.

How the code works

The function passed to sort() compares two items. It returns 1 when the first label is greater, -1 when it is smaller and 0 when they are equal, so the items end up in A to Z order.

Points to note

  • sort() changes the original array. Here the original and the sorted array are the same object.
  • The comparison with > is case sensitive, so capital letters come before small letters.
  • Data from @wire or Apex is read only, so calling sort on it directly can throw an error.

Safer version

const sorted = [...this.arrayOfObjectsBeforeSort].sort((a, b) => a.label.localeCompare(b.label));

// Z to A
const descending = [...this.arrayOfObjectsBeforeSort].sort((a, b) => b.label.localeCompare(a.label));

// numbers
const byNumber = [...items].sort((a, b) => a.value - b.value);

The spread [...array] makes a copy, so the original stays unchanged. localeCompare sorts text correctly for upper and lower case letters and accented characters.

FAQ

Do I need @track?
No. Assigning the sorted array to a field is enough to refresh the screen.

How do I sort by two fields?
Compare the first field, and when the result is 0, return the comparison of the second field.

Leave a Reply