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

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)

Leave a Reply