Is there a javascript equivalent of the Multimap data structure?

ripper234 picture ripper234 · Jul 4, 2012 · Viewed 9.6k times · Source

Multimap is an data structure that maps a key to a list/set of values.

Is there a good, unobtrusive js library that implements this data structure?

Edit - I know I can implement it "easily" myself, but I believe having it as a standalone abstraction is a good thing, so answers to this questions should not be "just implement it yourself".

Answer

Svend picture Svend · Jul 4, 2012

Since @Esailija posted this as a comment only, I'll submit it as a possible answer. Objects using arrays as values is the way to go, and manipulate the values by way of Underscore.js.

var map = {
    foo: [1, 2, 3],
    bar: ['1', '2', '3']
};

map.foo = _.union(map.foo, [1, 4]); // map.foo -> [1, 2, 3, 4]

While it obviously depends on your needs, this approach gives you generic data structures that goes everywhere, and a library that works very nicely with collections and lists. For most purposes, performance of this approach should be just fine (just don't do it millions of times each second).