Home > Software engineering >  javascript array multiple sorting
javascript array multiple sorting

Time:08-16

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
   }
  ]

CodePudding user response:

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)

CodePudding user response:

Based on the solutions in How to sort 2 dimensional array by column value?, you can solve the problem by making two sort calls, such as

// Sort the 'min' first
cardItems= cardItems.sort(function(a,b) {
    return a.min - b.min;
});


// Sort the 'price' next
cardItems= cardItems.sort(function(a,b) {
    return a.price - b.price;
});

I didn't test the code, but you may see the idea.

  • Related