nimgwfc
nimgwfc

Reputation: 1509

Cannot sort array of objects by integer value

I have an array of objects that looks something like this:

[
    {
        "value": 351.68474,
        "o_p": [
            "$.text"
        ]
    },
    {
        "value": 348.0095,
        "o_p": [
            "$.text"
        ]
    },
    {
        "value": 365.2453,
        "o_p": [
            "$.text"
        ]
    }
]

I want to try to sort this object based on value and to do so, I have tried this:

const sorted_object = orig_object.sort((a, b) => a.value - b.value);

I found the above sorting strategy when looking at other answers on this site.

However, I get this error and I can't seem to figure it out:

ERROR TypeError: Cannot assign to read only property '0' of object '[object Array]'

Is there something obvious that I am doing wrong?

Upvotes: 0

Views: 136

Answers (1)

Kelvin Schoofs
Kelvin Schoofs

Reputation: 8718

The Array.prototype.sort method mutates the array. Based on the error, you seem to be dealing with a read-only array for some reason, hence the error when using the mutating .sort.

If a clone is fine, you can use [ ...array ].sort(...) to "clone-and-sort".

Upvotes: 1

Related Questions