0

I do not feel this is a duplicate. The only other answers are over five years old and am assuming methods have improved.

What is the proper way to find the minimum value in a named array. For example, if my array looks like this:

let drink_prices = [
{brandy:25, name: "brandy drink"},
{whiskey:20, name: "whiskey drink"},
{vodka:46, name: "vodka drink"}
];

How would I find the lowest price? I thought a funky for loop would do it, but wondered if there was a way to use Math.min() but didn't see a way for what I'm doing.

Advice?

SteveV
  • 351
  • 1
  • 6
  • 15
  • 1
    Are you asking for the corresponding key for that value, the value itself, or both? Also, this is an object, not a "named array". JavaScript has no associative arrays. – meager May 17 '18 at 20:28
  • `Math.min(...Object.values(drink_prices))` But do you want the fact is `whiskey`? – Keith May 17 '18 at 20:31
  • @meagar - I used the name "Named Array" as a visual reference as it wasn't the standard single value array. I am wanting the min value for all the "drinks", so in my example, "20" – SteveV May 17 '18 at 20:54
  • @Keith - all I need is min value, so the "20" in the example I gave. Don't need any of the "drink" names – SteveV May 17 '18 at 20:55
  • You've edited the question and now the object format is really inconvenient. If you have any control over it, the price should be a property of the object: `{price: 25, name: 'brandy'}`. It's a poor design choice to have different property names all pointing to the same sort of thing. – Mark May 17 '18 at 21:08
  • Your modified question would still be a duplicate of https://stackoverflow.com/questions/33351934/get-the-min-and-max-from-array-of-objects-with-underscore-js, https://stackoverflow.com/questions/11985132/how-do-you-find-min-max-of-a-property-in-an-array-of-objects-in-javascript, https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects etc. – meager May 17 '18 at 21:11
  • @Mark_M - yes, edited as it got marked as duplicate and I was forced to make it unique. I was trying to avoid a For Each loop but I do have control over the array so can simplify it to make things easier. – SteveV May 17 '18 at 21:17
  • You have now modified to use an array, but in a way that doesn't now make any sense, your key names keep changing.. You could do -> `Math.min(...drink_prices.map(v=>Object.values(v)[0]))`, but this is assuming the first key is the one your interested in. – Keith May 18 '18 at 00:53

0 Answers0