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.
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.
Share Improve this question asked Sep 9, 2018 at 11:20 Steve BennettSteve Bennett 127k45 gold badges186 silver badges243 bronze badges1 Answer
Reset to default 9You could use _.groupBy
for grouping by a given key.
Creates an object posed of keys generated from the results of running each element of
collection
thruiteratee
. The order of grouped values is determined by the order they occur incollection
. The corresponding value of each key is an array of elements responsible for generating the key. Theiteratee
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./ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>