Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get key with minimum value

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.

like image 452
Mernt Avatar asked Mar 25 '19 06:03

Mernt


People also ask

How do you get the key of the minimum value in a dictionary Python?

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.

How do you print a minimum value in Python?

In Python, you can use min() and max() to find the smallest and largest value, respectively, in a list or a string.

How do I find the value of a key?

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.

How do you find the maximum value of a dictionary?

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.


1 Answers

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);
like image 101
Jack Bashford Avatar answered Sep 17 '22 18:09

Jack Bashford