Sorting in Typescript (Simple Arrays & Array of Objects)

Hi Friends,

This post is not regarding the SharePoint but it is a very common functionality that we need in day to day coding. So I thought to write down here. This functionality is of sorting in Typescript.


Sorting simple Arrays

Sorting is the very basic functionality that is required and when it comes to typescript we do get OOB method, but that is for the simple array.

  
let fruits:string[] = ['Banana''Orange''Apple''Pineapple'] ;
  console.log(fruits.sort());


Output:
Apple, Banana, Orange, Pineapple


Sorting an Array of Objects

When it comes to sorting the array of objects, we do not have any OOB method which can serve our purpose. for this, we have to write our small custom logic within the sort method


let fruits: any[] = [{ Name: 'Banana' }, { Name: 'Orange' }, 
{ Name: 'Apple' }, { Name: 'Pineapple' }];

  console.log(fruits.sort((leftright): number => {
    if (left.Name < right.Name) return -1;
    if (left.Name > right.Name) return 1;
    return 0;
  }));


Output:
{Name: 'Apple'},{Name: 'Banana'}, {Name: 'Orange'}, {Name:'Pineapple'}

This logic will sort the array in ascending order if you want to get the values in descending just swap the return values in both the conditions (if statements)

Known Issue:

One of the issues I encountered is when there is space in the text, in the beginning, then it sorts considering the space and you'll not get the expected result, so do not forget to trim the values if there is even a slightest percent of possibility.


Happy Coding.!!
#Typescript #SharePointWidgets

Comments

Popular posts from this blog

Rename Folder using Microsoft Flow / Power Automate in a Document Library in SharePoint Online

Power Automate: How to Add "New Line" to the text in SharePoint multiline text field

Power Automate: Rename file in SharePoint Online