Home > Software engineering >  filtering an array: get max price and unique objects?
filtering an array: get max price and unique objects?

Time:03-31

store = [{
    "item": "shirt",
    "price": 20
  },
  {
    "item": "shirt",
    "price": 50
  },
  {
    "item": "pants",
    "price": 10
  },
  {
    "item": "pants",
    "price": 20
  }

]
//im filtering the array to get objects without duplication here
console.log(store.filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i))

and i would like to get the max price as well in the same filter so how would i get this output after excuting it ?

expected output:

[{
    "item": "shirt",
    "price": 50
 },
 {
    "item": "pants",
    "price": 20
}]

CodePudding user response:

You could sort() them by price before filtering.

store = [{
    "item": "shirt",
    "price": 20
  },
  {
    "item": "shirt",
    "price": 50
  },
  {
    "item": "pants",
    "price": 10
  },
  {
    "item": "pants",
    "price": 20
  }
]

const result = store.sort((a, b) => b.price - a.price).filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i);


console.log(result);

CodePudding user response:

I like @axtck's answer. .... Having filtered the objects, now use .map() to find from the original data the max price by sorting:

.map(
    ({item,price}) => 
    ({item,price:store.filter(p => p.item === item).sort((a,b) => b.price - a.price)[0].price})
)

store = [{
    "item": "shirt",
    "price": 20
  },
  {
    "item": "shirt",
    "price": 50
  },
  {
    "item": "pants",
    "price": 10
  },
  {
    "item": "pants",
    "price": 20
  }

]
//im filtering the array to get objects without duplication here
console.log(
    store.filter((v, i, a) => a.findIndex(v2 => ['item'].every(k => v2[k] === v[k])) === i)
    .map(
        ({item,price}) => 
        ({item,price:store.filter(p => p.item === item).sort((a,b) => b.price - a.price)[0].price})
    )
)

CodePudding user response:

You could use Array.reduce() to get the highest price for each item.

We'd enumerate through each value, creating a map object, and if no entry exists for that item or the existing entry has a lower price, we'd update:

const store = [{ "item": "shirt", "price": 20 }, { "item": "shirt", "price": 50 }, { "item": "pants", "price": 10 }, { "item": "pants", "price": 20 } ]

const result = Object.values(store.reduce((acc, { item, price }) => {
    // Either item does not exist or has a lower price... 
    if (!acc[item] || acc[item].price < price) {
       acc[item] = { item, price };
    }
    return acc;
}, {}))

console.log(result)
.as-console-wrapper { max-height: 100% !important; }

  • Related