Search code examples
javascriptarrayslodash

Lodash group by specific words/prefix in a key


I wonder how I can group this array based on the prefix text in name key (split the name key at the : colon) using Lodash.

const tags = [
  { name: 'Animals: Frogs', id: 1 },
  { name: 'Animals: Lions', id: 2 },
  { name: 'Birds: Crows', id: 3 }
];

to

const tags = [{ 
  animals: [
    { name: 'Frogs', id: 1 },
    { name: 'Lions', id: 2 },
  ],
  birds: [
    { name: 'Crows', id: 3}
  ]
}];

Does Lodash have any functions to handle this, or is a custom function/regex needed?


Solution

  • If the pure JS suffices, it can be done this way (the result is an object here, not an array, but this can be changed if needed):

    const tags = [
      { name: 'Animals: Frogs', id: 1 },
      { name: 'Animals: Lions', id: 2 },
      { name: 'Birds: Crows', id: 3 }
    ];
    
    const tags2 = tags.reduce(
      (acc, { name, id }) => {
        let [group, type] = name.split(': ');
        group = group.toLowerCase();
        acc[group] ??= [];
        acc[group].push({ name: type, id });
        return acc;
      },
      {},
    );
    
    console.log(tags2);