Hi I have a very long list of key value pairs in json key:value, key:value and so on
car <--> wheel
wheel <--> tyre
bed <--> sheets
guitar <--> strings
guitar <--> pickup
tyre <--> rubber
What I want is to group all relations into arrays no matter how distant like this
[car, wheel, tyre, rubber]
[guitar, strings, pickup]
[bed, sheets]
What is an efficient way to do this with Javascript?
First of all, I would store the relationships as arrays so that you can have duplicate "keys." Key methods: an initial dictionary including every word related to each individual word; a recursive chain expander using map and reduce; filtering chains based on equivalency.
I'd go with a map of words, linking the sets they are currently in. The map (a javascript object) with nearly O(1) runtime for accessing a key should help the performance. Start with the same format as proposed by @matt3141:
This will split your graph in its connected components (In the
setsByWord
object these component arrays are indexed by the nodes):If you have a directed graph, and want arrays of all successors by word, you could use this:
If you are sure to have no circles in the graph and only want lists for the beginners of paths, you might add this: