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

Array.sort() on multiple properties

I have an array, productData with multiple properties. This is how I currently sort the array by monthlyCost, ascending.
How can I modify this to sort all items by a boolean property isPromoted, followed by monthlyCost?
My array should start with all items where isPromoted == true sorted by monthlyCost, then all items where isPromoted == false sorted by monthlyCost.

    productData.sort((a, b) => {
      if (a.monthlyCost > b.monthlyCost) {
        return 1;
      } else if (a.monthlyCost < b.monthlyCost) {
        return -1;
      } else {
        return 0;
      }
    });

>Solution :

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

You can use this callback:

productData.sort((a, b) => +b.isPromoted - +a.isPromoted || a.monthlyCost - b.monthlyCost);

The unary plus is optional in plain JavaScript, but in a TypeScript context, you’ll need to be explicit about the conversion to number and apply +.

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