It depends!
How big N and M could be? If they are low enough, just write the code that is more easy to read and understand by everyone.
And for example, the last one, although short, it requires to know about the keyBy of lodash. Sadly I am a user of underscore, so I do not know what it does XD (in fact, I hate the AD that has lodash and hides what you want to read, I do not why).
I remember that there was an early video about React, in they explained that they did not want to use lodash or similar libraries to reduce the minimal the api surface area. It was a very good talk: