0

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?

1 Answer 1

1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.