Skip to content

Instantly share code, notes, and snippets.

@smokeyfro
Created January 21, 2021 09:22
Show Gist options
  • Save smokeyfro/aab87375ba107b45f61bacff1b5b3721 to your computer and use it in GitHub Desktop.
Save smokeyfro/aab87375ba107b45f61bacff1b5b3721 to your computer and use it in GitHub Desktop.
Group posts by year with method only
<template>
<Layout>
<h1>Group by Year via method</h1>
<ul>
<li v-for="(items, year) in groupBy($page.allBlogPost.edges, 'createdYear')" :key="year">
{{ year }}
<ul>
<li v-for="item in items" :key="item.id">
{{ item.title }}
</li>
</ul>
</li>
</ul>
</Layout>
</template>
<script>
export default {
metaInfo: {
title: 'Hello, world!'
},
methods: {
/*!
* Group items from an array together by some criteria or value.
* (c) 2019 Tom Bremmer (https://tbremer.com/) and Chris Ferdinandi (https://gomakethings.com), MIT License,
* @param {Array} arr The array to group items from
* @param {String|Function} criteria The criteria to group by
* @return {Object} The grouped object
*/
groupBy(arr, criteria) {
return arr.reduce(function (obj, item) {
// set the node element as item
// otherwise we have to use `item.node` everywhere in the code
item = item.node;
// Check if the criteria is a function to run on the item or a property of it
var key = typeof criteria === 'function' ? criteria(item) : item[criteria];
// If the key doesn't exist yet, create it
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
// Push the value to the object
obj[key].push(item);
// Return the object to the next item in the loop
return obj;
}, {});
}
}
}
</script>
<page-query>
query {
allBlogPost {
edges {
node {
id
title
createdYear: created(format: "Y")
created
category {
title
}
}
}
}
}
</page-query>
<style>
.home-links a {
margin-right: 1rem;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment