I would like to group an array according to its first letter (alphabetically) so the output looks something like this:
const words = ['Apple', 'Ape', 'Banana', 'Bag', 'Crab', 'Cupboard', 'Dog', 'Dare'];
[
{ 'A' : [ 'Apple', 'Ape' ] },
{ 'B': [ 'Banana', 'Bag' ] },
{ 'C': [ 'Crab', 'Cupboard' ] },
{ 'D': [ 'Dog', 'Dare' ] }
]
How would I do this using the groupBy Lodash method? Also in such a way that it could extend to all letters of the alphabet if needed? Would you also use the forEach Lodash method as well?
Thanks in advance!
With lodash you can use multiple methods to get it.
const words = ['Apple', 'Ape', 'Banana', 'Bag', 'Crab', 'Cupboard', 'Dog', 'Dare'];
const grouped = _.map(_.entries(_.groupBy(words, _.first)), ([k,v]) => ({[k]:v}))
console.log(grouped);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
With plain old JavaScript:
const words = ['Apple', 'Ape', 'Banana', 'Bag', 'Crab', 'Cupboard', 'Dog', 'Dare'];
const grouped = Object.values(words.reduce((acc,word) => (acc[word[0]] ??= {[word[0]]: []}, acc[word[0]][word[0]].push(word), acc), {}))
console.log(grouped);