1

I have problem in order to sort an arry of object by two difrent keys. I want to sort this arry by price and if multi prices were same then sort them by time. I have some thing like this array:

var myArr = [
{"value":5 , "price"=10, "time":3},
{"value":1.5 , "price"=2, "time":2},
{"value":3 , "price"=5, "time":4},
{"value":1 , "price"=2, "time":1}
]

and after sort have to be something like this:

var myArr = [
{"value":1 , "price"=2, "time":1},
{"value":1.5 , "price"=2, "time":2},
{"value":3 , "price"=5, "time":4},
{"value":5 , "price"=10, "time":3}
]

I had tried many ways but I can't solve it since it's related to two keys at the same time.

Chinez
  • 551
  • 2
  • 6
  • 29
asd
  • 27
  • 4
  • *i had tried many ways* Great, then add the code that you have tried... – DecPK Jul 21 '21 at 14:17
  • 1
    Does this answer your question? [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) – Thomas Junk Jul 21 '21 at 14:17

1 Answers1

0

You can make use of Array.sort to first sort by price, then time:

var myArr=[{value:5,price:10,time:3},{value:1.5,price:2,time:2},{value:3,price:5,time:4},{value:1,price:2,time:1}];

myArr.sort((a, b) => {
  return a.price - b.price || a.time - b.time;
});
console.log(myArr);
Spectric
  • 30,714
  • 6
  • 20
  • 43