Coding⏱️ 3 min read📅 2026-06-04

How to Fix: Error while sorting array of objects Cannot assign to read only property '2' of object '[object Array]'

Error while sorting array of objects Cannot assign to read only property '2' of object '[object Array]'

Quick Answer: The issue arises from trying to sort an array of objects directly. Use the spread operator or destructuring to fix it.

The error 'Cannot assign to read only property '2' of object '[object Array]''' occurs when attempting to sort an array of objects using the `sort()` method. This issue affects developers who are unfamiliar with JavaScript's nuances or those working with legacy codebases.

This error can be frustrating, especially when trying to implement a seemingly simple task like sorting data. However, understanding the root cause and applying the correct solution will resolve the issue.

⚠️ Common Causes

  • The primary reason for this error is that the `sort()` method is being called on an array literal, which returns a new array object instead of modifying the original array. This causes the error because arrays are not objects in JavaScript, and attempting to assign to a read-only property results in the error.
  • Another possible cause is that the array contains other types of data besides objects, which can lead to unexpected behavior when trying to sort.

🛠️ Step-by-Step Verified Fixes

Using the `Array.prototype.sort()` method with an arrow function

  1. Step 1: Replace the original `sort()` call with the following code: `array.sort((a, b) => { return b.stats.speed - a.stats.speed });` This ensures that the correct array object is being sorted.
  2. Step 2: Verify that the array only contains objects and that all properties are numeric. If the array contains non-numeric values, consider using a different sorting method or data transformation.
  3. Step 3: Test the code to ensure it produces the desired output.

Using the `Array.prototype.sort()` method with a traditional function

  1. Step 1: Replace the original `sort()` call with the following code: `array.sort(function(a, b) { return b.stats.speed - a.stats.speed; });` This ensures that the correct array object is being sorted.
  2. Step 2: Verify that the array only contains objects and that all properties are numeric. If the array contains non-numeric values, consider using a different sorting method or data transformation.
  3. Step 3: Test the code to ensure it produces the desired output.

🎯 Final Words

By understanding the root cause of the error and applying one of the provided solutions, developers can resolve the 'Cannot assign to read only property '2' of object '[object Array]''' issue. Remember to always verify that your array contains only objects with numeric properties when sorting.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions