Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the key of the min value in a hash with underscore

I would like to find the key of a minimum value with underscore. For example:

var my_hash = {'0-0' : {value: 23, info: 'some info'},
              '0-23' : {value: 8, info: 'some other info'},
              '0-54' : {value: 54, info: 'some other info'},
              '0-44' : {value: 34, info: 'some other info'}
              }
find_min_key(my_hash); => '0-23'

How can I do that with underscorejs ?

I've tried:

_.min(my_hash, function(r){
  return r.value;
});
# I have an object with the row, but not it's key
# => Object {value: 8, info: "some other info"}

I also try to sort it (and then getting the first element):

_.sortBy(my_hash, function(r){ 
  return r.value; 
})

But it returns an array with numerical indexes, so my hash keys are lost.

like image 797
Benjamin Crouzier Avatar asked Dec 09 '22 09:12

Benjamin Crouzier


1 Answers

With Underscore or Lodash < 4:

_.min(_.keys(my_hash), function(k) { return my_hash[k].value; }); //=> 0-23

With Lodash >= 4:

_.minBy(_.keys(my_hash), function(k) { return my_hash[k].value; }); //=> 0-23

Without a library:

Object.entries(my_hash).sort((a, b) => a[1].value - b[1].value)[0][0]

or

Object.keys(my_hash).sort((a, b) => my_hash[a].value - my_hash[b].value)[0]

like image 115
James Kyburz Avatar answered Dec 10 '22 23:12

James Kyburz