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

javascript array multiple sorting

I want to sort by 2 key values ​​of object in javascript

    [
   {
    "min": 8,
    "price": 2
   },
   {
    "min": 3,
    "price": 1
   },
   {
    "min": 9,
    "price": 4
   },
   {
    "min": 360,
    "price": 9
   }
  ]

I want to sort from descending to ascending according to min and price values.
the code i wrote

const sortCardItems = cardItems
    .slice()
    .sort(
        (a, b) =>
            parseInt(a.min, 10) - parseInt(b.min, 10) &&
            parseInt(a.price, 10) - parseInt(b.price, 10),
    );

but it only sorts by price I want to get a result like this

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

e.g.

[
   {
    "min": 3,
    "price": 2
   },
   {
    "min": 4,
    "price": 3
   },
   {
    "min": 5,
    "price": 4
   },
   {
    "min": 360,
    "price": 9
   }
  ]

>Solution :

The easiest way to do it is to first get the difference between min and mins are equal, return the difference between prices

const data = [{
    "min": 8,
    "price": 2
  },
  {
    "min": 3,
    "price": 1
  },
  {
    "min": 9,
    "price": 4
  },
  {
    "min": 360,
    "price": 9
  }
]

data.sort((a, b) => {
  return a.min - b.min || a.price - b.price
})

console.log(data)
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