Search code examples
javascriptobjectlodash

Multiple version of keyBy in lodash? (Group values sharing a key as an array)


Is there a simple way to achieve this with lodash?

_.something([{a: 3, b: 4}, {a: 3, b: 5}, {a: 10}], 'a')

=> { 3: [ {a: 3, b: 4}, {a: 3, b: 5 } ], 10: [{ a: 10 }]}

That is, group all the values that share the same key together as an array under that key.


Solution

  • You could use _.groupBy for grouping by a given key.

    Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

    console.log(_.groupBy([{ a: 3, b: 4 }, { a: 3, b: 5 }, { a: 10 }], 'a'));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>