M00HY
M00HY

Reputation: 172

i need to sort array of objects in Vue with to attributes of the object but Vue go in infinite loop to sorting

vue js sort array of object with attribute and try to sort that sorted array with another attribute but Vue go in infinite loop of sorting

chatRoomArraySorted: function() {
    console.log("func name chatRoomArraySorted");

    function compare(a, b) {
        if (a.name < b.name)
            return -1;
        if (a.name > b.name)
            return 1;
        return 0;
    }

    return this.chatRoomsArray.sort(compare);
}

sortedArray: function() {
    this.log("sortedArray");

    function compare1(a, b) {
        return new Date(b.lastMsg.createdAt) - new Date(a.lastMsg.createdAt);
    }

    return this.chatRoomsArray.sort(compare1);
},

Upvotes: 4

Views: 1081

Answers (1)

thanksd
thanksd

Reputation: 55644

Computed properties will update whenever the value of any of the properties they depend on changes, meaning the defining function will be called again.

Since you are calling sort() on the chatRoomsArray property in both of your computed properties, you are mutating the chatRoomsArray array itself, triggering both computed properties to be updated. This will happen every time the function for each computed property runs, which is creating the infinite loop.


What you'll need to do is return a sorted copy of chatRoomsArray in each computed property without actually sorting the array itself.

You can make a copy of the array by calling concat() like so:

return this.chatRoomsArray.concat().sort(compare);

You could also use spread syntax to make a copy like so:

return [...this.chatRoomsArray].sort(compare);

Upvotes: 5

Related Questions