DEV Community

Cover image for Advent of code - Day 21

Advent of code - Day 21

qmenoret profile image Quentin Ménoret ・2 min read

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

Thank you for the break after Day #20 horrors 🙏
This one was clear, easy to work with and just challenging enough for a Monday!

Part 2 was actually free if you anticipated a little bit while doing the first part, so after reading the subject, it only took me 30 seconds to adapt the return value (since I already knew which allergens and ingredients were linked).

Anyway, here is my solution for day #21:

const lines = input.split('\n').map((line) => {
    const [_ingredients, _allergens] = line.split(' (')
    return {
      ingredients: _ingredients.split(' '),
      allergens: _allergens.slice(9, -1).split(', '),

  const allAllergens = Array.from(new Set(lines.reduce((acc, line) => [...acc, ...line.allergens], [])))
  const allIngredients = Array.from(new Set(lines.reduce((acc, line) => [...acc, ...line.ingredients], [])))

  const struct = allAllergens.reduce((acc, allergen) => {
    acc[allergen] = [...allIngredients]
    return acc
  }, {}) => { => {
      if (line.allergens.includes(allergen)) {
        struct[allergen] = struct[allergen].filter((ingredient) => line.ingredients.includes(ingredient))

  while (true) {
    let found = false => {
      if (struct[foundAllergen].length === 1) {
        const foundIngredient = struct[foundAllergen][0] => {
          if (allergen === foundAllergen) return
          if (struct[allergen].includes(foundIngredient)) {
            found = true
            const index = struct[allergen].indexOf(foundIngredient)
            struct[allergen].splice(index, 1)

    if (!found) break

      .map((allergen) => struct[allergen][0])
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!

Photo by Markus Spiske on Unsplash

Discussion (0)

Forem Open with the Forem app