Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

javascript push removing previous item from array

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

0 likes
2 replies
sustained's avatar

Please create a minimal "working" example with some actual example data using a tool like JSFiddle or CodePen.

This will help people to help you.

Gabotronix's avatar
Gabotronix
OP
Best Answer
Level 8

I decide to make moments a plugin so I can use it everywhere, this is my final code.

postsByMonth: (state) => {
        let months = { Enero:[], Febrero:[], Marzo:[], Abril:[], Mayo:[], Junio:[], Julio:[], Agosto:[], Septiembre:[], Octubre:[], Noviembre:[], Diciembre:[] }
        
        _.forEach(state.posts, function (post) {
            let month = _.upperFirst(Vue.moment(post.created_at).format('MMMM'));
            //alert(month);
            months[month].push(post)
        });
        
        return months
    },

I have a question, in my previous getter I was mutating my state, so in order for getters to work as they should I should return a new variable like I do here right??

Please or to participate in this conversation.