Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort array object based on property and its sort order in Angular 16+

I need to sort an object array based on the status in angular 16+. My status order should be [N-Op, Used, Unknown, Op]
Sample object :

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
  ];

How could I achieve the expected result as below.

const stockList = [
    {
      'heading': 'SK',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'N-Op',
    },
    {
      'heading': 'Bugati',
      'status': 'Unknown',
    },
    {
      'heading': 'SKU',
      'status': 'Op',
    },
    {
      'heading': 'Uniliver',
      'status': 'Op',
    }
  ]; 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should work with Array.prototype.sort() and defining the custom logic to compare the index from the sortOrder array.

Assume that all values of status existed in sortOrder array.

const sortOrder = ["N-Op", "Used", "Unknown", "Op"];

let sortedStockList  = stockList.sort((a, b) => {
    let xIndex = sortOrder.indexOf(a.status);
    let yIndex = sortOrder.indexOf(b.status);

    if (xIndex < yIndex)
        return -1;
    else if (xIndex > yIndex)
        return 1;
    else
        return 0;
});

(Optional) If you want the sort followed by heading, you can replace return 0; with

return a.heading.localeCompare(b.heading);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading