Group data in a list custom component

Hello community!

I was wondering if anyone has ever had to group data using the custom component. It’s not a native function of the custom component so I’m looking for creative solutions here. Any ideas are welcome!

TIA!

Yeah, it sound like i did this earlier, can you please describe what you exactly want ?

I was trying to achieve grouping table data by one of the fields. For example, if you have a table with a user connection, and there is multiple records with the same users, i would like to group those records by user.

Basically the same as a table component groups records but with a custom component.

You can try using a custom Handlebars Helper.

In your Javascript of the page add this:


Handlebars.registerHelper('group_by', function(items, field, options) {
  const groups = {};
  items.forEach(item => {
    const value = item[field];
    groups[value] = groups[value] || [];
    groups[value].push(item);
  });
  
  let result = '';
  for (const group in groups) {
    result += `<h2>${group}</h2>`; // Group header, e.g., the value of field_65
    groups[group].forEach(item => {
      result += options.fn(item); // Render each item in the group
    });
  }
  return result;
});

Then in the code of the custom component, switch it from:

{{#each records}}
  Your custom code etc... 
{{/each}}

To something like this (field_42 is what I will be grouping by):

{{#group_by records "field_42"}}
  
  {{field_65}}<br>
  
{{/group_by}}

Here’s how you can have more fun with this:
https://chat.openai.com/share/050ef550-f267-499a-9239-8f1e3aa9a792

1 Like

Ill give it a go! Thanks @moe!

Awesome! It works great, I love handlebars! Thanks again Moe

1 Like