← Snippets

Group By

 type Article = {
  title: string
  year: number
}

const articles: Article[] = [
  { title: 'Digital Garden', year: 2021 },
  { title: 'Working Remotely', year: 2022 },
  { title: 'Reducer Pattern', year: 2022 },
  { title: 'From Tailwind CSS to PandaCSS', year: 2023 },
  { title: 'Poeta Digital', year: 2023 },
  { title: 'International Phonetic Alphabet', year: 2024 },
  { title: 'Building Tree Family with D3', year: 2024 }
]
 

Group by with .reduce()

 const result = articles.reduce((prev, current) => {
  if (!prev[current.year]) {
    prev[current.year] = []
  }
  prev[current.year].push(current)
  return prev;
}, {} as Record<number, Article[]>)
 

Group by with Object.groupBy

 const result = Object.groupBy(articles, ({year}: {year: number}) => year)
 

Result

 console.log(result)
/* Result is:
{
  2021: [
    { title: 'Digital Garden', year: 2021 }
  ],
  2022: [
    { title: 'Working Remotely', year: 2022 },
    { title: 'Reducer Pattern', year: 2022 }
  ],
  2023: [
    { title: 'From Tailwind CSS to PandaCSS', year: 2023 },
    { title: 'Poeta Digital', year: 2023 }
  ],
  2024: [
    { title: 'International Phonetic Alphabet', year: 2024 },
    { title: 'Building Tree Family with D3', year: 2024 }
  ],
}
*/