javascript push removing previous item from array

Posted 3 months ago by Gabotronix

Hi, I have a collection of posts wich I want to group by month of creation (created_at), to do this I'm looping through each post, parsing the date using moments plugin and pushing to the correct array, however there's a problem, I end up with an array of 12 items (months) with only one post per month, I think this is because when I push into array the previous item gets replaced.

My logic:

import axios from 'axios';
import _ from 'lodash';
//STATE
const state = {
    posts: [],
    months : { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] },
    postcategories: [],
    loadingStatus:0,
    
}

//GETTERS
const getters = {

    
    postsByMonth: (state) => {
        return _.forEach(state.posts, function(post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));
            state.months[month].push(post);
        });
    },

}

I end up with this, as you can see they aren't even properly grouped:

https://i.imgur.com/5CDAfzn.png

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.