14

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".

ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 5
    Object that has arrays as values? – Esailija Jul 04 '12 at 12:40
  • + toss in [Underscore.js](http://underscorejs.org/), and you're good to go! – Svend Jul 04 '12 at 12:54
  • @Esailija, in Java you can use `Map>`, but someone obviously thought multimap is important enough to code it in Java. Why not JS? http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html – ripper234 Jul 04 '12 at 16:54
  • You may try to use [**multimap.js**](http://code.google.com/p/backplanejs/source/browse/third-party/uxf/src/lib/_backplane/multimap.js?r=e436949ff2516d2c15fbd8d31f5da7744ed5cb93). – Clément Andraud Jul 04 '12 at 12:38
  • @ClémentAndraud Should be adapted as it requires `UX.Class`. – Florent Jul 04 '12 at 12:47
  • In line with `Map>`, you can use a `Map` with `Array` values in newer JS environments, or a `Map` with `Set` values if you want to ignore duplicates. – Mark K Cowan Oct 18 '16 at 17:07
  • You can make your own MultiMap in es2015 by extending Map. Like this: https://jsfiddle.net/johnsonjo4531/j5zjchmb/1/. Note babel doesn't support extending builtins so you'll just have to deal with the support that es2015 has. – John Nov 25 '17 at 23:10

1 Answers1

3

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

Svend
  • 7,916
  • 3
  • 30
  • 45
  • 1
    See my comment: the ability to implement it using a List and an Array is not an excuse not to have a "go-to" multimap class. Sure, I might use this instead of writing one from scratch, but if a library I was already using (e.g. jQuery) had a multimap class, I'd rather use that than play with arrays myself. – ripper234 Jul 04 '12 at 16:56