0

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

0

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

@Jack_Hu OP input data is different from output data. I used the input.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.