1

I have this array with several different products, could be up to 100 different products. I could have same product with different prices and different products. I need to get the highest price on each batch.

This is a sample array

arrayOfProducts = [
 {
   product: {
     batch: 11201,
     price: 745
   }
 },
 {
  product: {
      batch: 11201,
      price: 746
    }
 },
 {
  product: {
      batch: 11201,
      price: 747
    }
 },
 {
  product: {
      batch: 11202,
      price: 748
    }
 },
 {
  product: {
      batch: 11202,
      price: 749
    }
 },
 {
  product: {
      batch: 11202,
      price: 750
    }
 }
]

And this is what I want to see as a result after filtering through it

filteredArrayOfProducts = [
{
  product: {
    batch: 11201,
    price: 747
  }
},
{
  product: {
    batch: 11202,
    price: 750
  }
}
]
Isen
  • 425
  • 1
  • 5
  • 13
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 06 '21 at 22:43
  • 1
    [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+filter+objects+by+highest+value+for+key) of [JS: Filter array of objects by max value per category](/q/56901732/4642212). – Sebastian Simon Aug 06 '21 at 22:43
  • Don't you think it's better to store the objects containing the data directly without the `product` property? You will end up with an array of objects with each one containing 2 properties `batch` and `price`. It would be easier to filter that array. – Ikdemm Aug 06 '21 at 22:48
  • This is an oversimplification, the real objects are massive, but I need to filter them by those two properties – Isen Aug 06 '21 at 23:36
  • @SebastianSimon Thanks, but in my case the object is nested and I don't know how to address that – Isen Aug 06 '21 at 23:40
  • const result = Object.values(arrayOfBids.reduce((r, o) => { r[o.nft.batch] = (r[o.batch] && r[o.batch].price > o.price) ? r[o.batch] : o return r }, {})) – Isen Aug 06 '21 at 23:47
  • Thanks @SebastianSimon with your link I worked it out – Isen Aug 06 '21 at 23:47

0 Answers0