I have a long dictionary with many entries {y:10, au:41, w:41, m:11, u:21, t:1, d:1}
What i need is to get all keys with the lowest value in a array. I found this (Getting key with the highest value from object) but that doesn't work for multiple minimums(maximums)
and i need to use only core javascript.
The fastest and easiest is probably to get the objects keys as an array with Object.keys, and filter that array based on items having the lowest value.
One would need to find the lowest value first, then filter, here's one way to do that
var obj = {y:10, au:41, w:41, m:11, u:21, t:1, d:1};
var keys = Object.keys(obj);
var lowest = Math.min.apply(null, keys.map(function(x) { return obj[x]} ));
var match = keys.filter(function(y) { return obj[y] === lowest });
document.body.innerHTML = '<pre>' +JSON.stringify(match, null, 4)+ '</pre>';
Getting the keys, then creating a array of the values that is passed to Math.min.apply to get the lowest value in the object.
Then it's just a matter of filtering the keys for whatever matches the lowest value in the object.
Here's another way using sort
var obj = {y:10, au:41, w:41, m:11, u:21, t:1, d:1};
var keys = Object.keys(obj).sort(function(a,b) { return obj[a] - obj[b]; });
var match = keys.filter(function(x) { return obj[x] === obj[keys[0]]; });
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