Search code examples
javascriptarraysecmascript-6javascript-objects

get a single object from an array, according to condition by one of its keys


I have an array of objects and I would like to obtain only the object that has the largest quantity, in this example the object with 'id': 4, and trying to use the filter property of javascript, but I have not achieved it, otherwise I can to achieve this?

[
  {
    "id": 1,
    "quantity": 10,
    "price": 80
  },
  {
    "id": 2,
    "quantity": 30,
    "price": 170
  },
  {
    "id": 3,
    "quantity": 50,
    "price": 230
  },
  {
    "id": 4,
    "quantity": 100,
    "price": 100
  }
]

Solution

  • In this case, reduce is the right choice:

    const most = array.reduce((a, b) => a.quantity > b.quantity ? a : b);