I frequently work with object hashes whose values are one-dimensional arrays (vectors). I've written a function using lodash/underscore (NB. only tested with lodash) that performs an array-aware invert
, whose output object has keys that are the unique elements of the input object's value vectors, and values that are the input object's keys.
(NB. I can't use lodash'slodash/underscore's built-in invert
with an object hash with array-valued keys because the resulting object has stringified keys which simply stringify the arrays—an output object key might be [1, 2, 3].toString()
, and entirely useless.)
Lodash's flatten
is used to remove one level of nesting, i.e., transform [[[k1, v1]], [[k2, v2], [k3, v3]]]
to [[k1, v1], [k2, v2], [k3, v3]]
.
Finally lodash's object
is called to convert this list of 2-tuple key-value pairs into an object hash.