Home > Back-end >  Group an array by its first letter - using groupBy method (Lodash)
Group an array by its first letter - using groupBy method (Lodash)

Time:11-23

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!

CodePudding user response:

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/[email protected]/lodash.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You don't need lodash:

const words = ['Apple', 'Ape', 'Banana', 'Bag', 'Crab', 'Cupboard', 'Dog', 'Dare'];

const uniqueLetters = [...new Set(words.map(w => w[0]))];
const grouped = uniqueLetters.map(l => {
  const el = {};
  el[l] = words.filter(w => w[0] == l);
  return el;
})

console.log(grouped);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Or, in linear big O time:

const words = [
  "Apple",
  "Ape",
  "Banana",
  "Bag",
  "Crab",
  "Cupboard",
  "Dog",
  "Dare"
];

const uniqueLetters = [...new Set(words.map(w => w[0]))];
const el = {};
uniqueLetters.forEach(l =>  el[l] = []);
words.forEach(w => el[w[0]].push(w));
const arr = Object.keys(el).map((k) => {
  const a = {};
  a[k] = el[k];
  return a;
});

console.log(arr);
  • Related