Search code examples
vue.jsvuex

Vuex: Can't tell why my getter is not sorting properly


store.js

getComments(state) {
   let allComments = state.allComments;

    allComments = allComments.sort((a, b) => {
        return a.stamped > b.stamped;
    });
    
     return allComments;
}

allComments is an array of objects that are comments and stamped is a timestamp field on them.

They are being returned as follows: [{stamped: 1595893492}, {stamped:1595893432}, {stamped: 1595893496}].
It's not even in increase or decreasing order...the lowest (oldest) is the 2nd value returned.


Solution

  • Two problems...

    1. You are mutating state in your getter
    2. Your comparison function is returning a boolean but it should return an integer

    You can solve both of these using the following

    getComments: state => [...state.allComments].sort((a, b) => a.stamped - b.stamped)
    

    The spread-operator creates a shallow copy of your allComments state property so you're no longer mutating it with sort.

    See Array.prototype.sort() for an understanding of comparators and the value they should return.