Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

231
Views
Group an array by its first letter - using groupBy method (Lodash)

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!