Grouping things in Svelte

- Posted in development svelte

Here’s a code trick I would like to share.

I was making a configurator for Mono’s Figma workshop. You can view the result in this Svelte REPL.

This is a proof of concept where people can pick and choose their own modules, by making a selection. And this selection consists of groups. I want to disclaim here to not see this as a final result or a communication of the actual pricing etc. This is a work in progress.

(If you are interested in a Figma workshop, for now it’s best to get in touch with Mono for a custom quote.)

Now that we have that out of the way, let’s focus on the interesting code in the REPL. Specifically, grouping things. If you have a design where you see things divided in groups, you might be tempted to put that into the data structure itself:

let data = [
  {
    category: "Group A",
    contents: [
      {
        name: "Item 1",
        property2: true
      },
      {
        name: "Item 2",
        property2: false
      }
    ]
  },
  {
    category: "Group B",
    contents: [
      {
        name: "Item 1",
        property2: true
      },
      {
        name: "Item 2",
        property2: false
      }
    ]
  }
]

However, I find it is better to not do this, and to keep the data on a single level:

let data = [
  {
    name: "Item 1",
    property2: true,
    category: "Group A",
  },
  {
    name: "Item 2",
    property2: false,
    category: "Group A",
  },
  {
    name: "Item 1",
    property2: true,
    category: "Group B",
  },
  {
    name: "Item 2",
    property2: false,
    category: "Group B",
  }
]

Using a clever reduce function, you can then change up the data so you can loop over it with two loops, one for the groups and one for the items:

let groups = data.reduce((curr, val) => {
  let group = curr.find(g => g.category === `${val.category}`)
  if (group) {
    group.values.push(val)
  } else {
    curr.push({ category: `${val.category}`, values: [ val ] }) 
  }
  return curr
}, [])

In the above example, I am using category as a grouping property.

I made a REPL demo of the simplified example I am showing in this post.

I hope this helps someone out!

Leave a Reply

Your email address will not be published. Required fields are marked *