I have an array like this: arr = {lst1: 300, lst2: 381, lst3: 4, lst4: 4, lst5: 49, …}
And I'm trying get the lowest value with key using Javascript.
What I've tried:
alert(Math.min.apply(Math, arr));
returns Infinity
I don't know why
I got this on Google, just for try:
var keys = Object.keys(arr).map(Number).filter(function(a){
return arr[a];
}); alert(Math.min.apply(Math, keys));
returns Infinity
too
I want something more complete, like this output: "The lowest value is 2 from lst9".
I really tried fix it myself before asking here, but without success! Can you help me fix this "Infinity" issue? Thank you.
To find the minimum value in a Python dictionary you can use the min() built-in function applied to the result of the dictionary values() method.
In Python, you can use min() and max() to find the smallest and largest value, respectively, in a list or a string.
get() to get the default value for non-existent keys. You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.
You can get the key and value using Object.entries
:
var arr = {
lst1: 300,
lst2: 381,
lst3: 4,
lst4: 4,
lst5: 49
};
function lowestValueAndKey(obj) {
var [lowestItems] = Object.entries(obj).sort(([ ,v1], [ ,v2]) => v1 - v2);
return `Lowest value is ${lowestItems[1]}, with a key of ${lowestItems[0]}`;
}
var lowest = lowestValueAndKey(arr);
console.log(lowest);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With