Michael
Michael

Reputation: 443

Return object key with minimum property value

I have an object with multiple keys (e.g. idOne, idTwo, idThree, idFour) ... each key contains an array of objects. I would like to return and output the key with minimum price. In this example, idThree contains the minimum price of id and therefore should output idThree. I have code that returns the minimum price found ... but my goal is to return key (idThree). Is there a simpler/cleaner way?

const object = {
   idOne: [{ price: 300 }],
   idTwo: [{ price: 200 }, { price: 100 }],
   idThree: [{ price: 90 }, { price: 100 }],
   idFour: [{ price: 99 }, { price: 210 }]
}

Current Code

const arrayOfMinValues = []
for (const [key, value] of Object.entries(object)) {
  const minimumEntry = Math.min(...value.map(item => item.price))
  arrayOfMinValues.push(minimumEntry)
}

console.log('MIN VALUE IS: ', Math.min(...arrayOfMinValues)) // how can I return key?

Upvotes: 0

Views: 542

Answers (4)

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9213

Simple approach to use with steps:

  1. Create sumPrices() function to get sum of prices.
function sumPrices(arr){
    sum = 0;
    for(const price of arr){
        sum += price["price"]
    }
    return sum;
}
  1. Create variable keys has all keys. Create two vars minKey the key of lowest prices. and minSum sum of lowest prices.
const keys = Object.keys(object);
let minKey = null,
    minSum = Number.MAX_SAFE_INTEGER;
  1. iterate over array keys get each sum of each inner array and compare currentSum with minSum if less than minimum. keep track the minSum with thier recpective key.
for(const key of keys){
    const currentSum = sumPrices(object[key])
    if(currentSum <= minSum){
          minKey = key;
          minSum = currentSum;
    }
}
console.log(minKey);

Upvotes: 0

charlietfl
charlietfl

Reputation: 171690

Another variation of reduce() using find()

const object = {"idOne":[{"price":300}],"idTwo":[{"price":200},{"price":100}],"idThree":[{"price":90},{"price":100}],"idFour":[{"price":99},{"price":210}]}


const [key, lp] = Object.entries(object).reduce((a, [k, v])=>{
     const low = v.find(o => o.price < a[1]);    
     return low ? [k, low.price] : a;   
},[null,Infinity])

console.log(key, ' has low price of ',lp )

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371069

If you first turn the object into an array of entries, and turn each subarray into the single lowest price in the array, you can then .reduce to iterate over all of those lowest prices and pick out the entry with the lowest one:

const object = {
   idOne: [{ price: 300 }],
   idTwo: [{ price: 200 }, { price: 100 }],
   idThree: [{ price: 90 }, { price: 100 }],
   idFour: [{ price: 99 }, { price: 210 }]
}

const minEntry = Object.entries(object)
  .map(([key, arr]) => [key, Math.min(...arr.map(obj => obj.price))])
  .reduce((a, b) => a[1] > b[1] ? b : a);
console.log('Min entry:', minEntry);

To access a property of an array, use [index] where index is the index you want to access:

const key = minEntry[0]

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 192607

You can use nested reduce calls to get an object with the minimum key and value, and destructure the key:

const object = {"idOne":[{"price":300}],"idTwo":[{"price":200},{"price":100}],"idThree":[{"price":90},{"price":100}],"idFour":[{"price":99},{"price":210}]}

const { key } = Object.entries(object)
  .reduce((acc, [key, values]) =>
    values.reduce((r, { price }) => price < r.price ? { key, price } : r, acc)
  , { key: null, price: Infinity })

console.log(key)

Upvotes: 1

Related Questions