1

Let's say i have array of object like this :

var DATA = [
  {
    "id": "5",
    "price": 170
  },
  {
    "id": "1",
    "price": 170
  },
  {
    "id": "2",
    "price": 270
  },
  {
    "id": "8",
    "price": 70
  }
]

I would like to sort it by price in descending order, but if price was equal i would like to sort it by id in ascending order.

I don't know how to sort with id if price was equal.

DATA.sort(function(a, b){
    var priceA = a.price,
        priceB = b.price,
        idA = a.id,
        idB = b.id;
    if(priceA < priceB) return 1;
    if(priceA > priceB) return -1;
    return 0;
});

Thanks in advance

Enzo
  • 198
  • 2
  • 11

1 Answers1

2

You could chain the wanted sort order.

var data = [{ id: "5", price: 170 }, { id: "1", price: 170 }, { id: "2", price: 270 }, { id: "8", price: 70 }];

data.sort((a, b) =>
    b.price - a.price ||
    a.id - b.id
);

console.log(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392