How to solve a problem with Array.sort Cannot assign to read only property '0' of object

In my React App I’m getting an error in the sort functionality

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

I have no idea what the problem is and the functionality is this:

const preparedSites = useMemo(
      () =>
        sites
          .sort(sortSiteSelection(site))
          .map(elm => {
            const arr = [
              elm.siteId,
              elm.city,
              elm.state,
              elm.country,
              elm.address,
              elm.status,
            ];
            if (nearestSites.length)
              arr.push(
                nearestSites.find(s => s.closestSiteId === elm.siteId).distance,
              );
            return arr;
          })
          .sort((a, b) => a[6] - b[6]),
      [sites, site, nearestSites],
    );

The error happening on the .sort part and the ´sortSiteSelection´ is as follow

const nameCompare = (x, y) => x.name.localeCompare(y.name);
const cityCompare = (x, y) => x.city.localeCompare(y.city);
const compareCountry = s => (x, y) => {
  if (!s) return 0;

  if (x.countryCode === s.countryCode && y.countryCode === s.countryCode)
    return 0;
  else if (x.countryCode === s.countryCode) return -1;
  else if (y.countryCode === s.countryCode) return 1;
  else return x.countryCode.localeCompare(y.countryCode);
};

export const sortSiteSelection = selectedSite => {
  if (!selectedSite) {
    console.log('NULL FROM SORT SITE');
    return () => 0;
  }
  pipeSort(compareCountry(selectedSite), nameCompare, cityCompare);
};

The OBJ of site is just

{
 siteId,
 city,
 elm.state,
 country,
 address,
 status,

}

1 thought on “How to solve a problem with Array.sort Cannot assign to read only property '0' of object”

  1. I would say it’s because the array is in strict mode. You should create a copy of this array. There are multiple ways for that.

    [...sites].sort(sortSiteSelection(site))
    

    or

    sites.slice().sort(sortSiteSelection(site))
    

    I hope this solves the issue you’re facing

    Reply

Leave a Comment