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?
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))
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