Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Finding highest value in Map() vs Object

I've been using objects as hash tables and I've been getting the highest value from them by Objects.keys(foo).reduce((a,b) => foo[a] > foo[b] ? a : b) . However, I've switched to using Maps() . What is the ideal way to iterate through a Map object to get the highest value?

like image 829
user10108817 Avatar asked Dec 20 '25 13:12

user10108817


1 Answers

You can spread the values() into Math.max:

let m = new Map([['a', 2], ['b',4], ['c',6]])

console.log("Max:", Math.max(...m.values()))

If you need both the key and value, I think you are back to reduce() using the entries() for the map:

let m = new Map([['a', 2], ['b',4], ['c',6]])

console.log([...m.entries()].reduce((a, e ) => e[1] > a[1] ? e : a))
like image 153
Mark Avatar answered Dec 23 '25 07:12

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!