Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

To sort the data array, we can use many methods. Incorrect selection can lead to errors that are difficult to detect with uniform, standard-format test data. I would like to share some errors and solutions that I have encountered in a React project, as follows:

Bug Icon Transparent PNG Image  Object array sorting
Sorting a read-only array is OK if it has only 1 or 0 items.
But if the array has 2+ items, attempting to sort it will cause a TypeError.
 
Example:  Sort object array data from API response in ascending order by item name
 
Input array:
[{ id: '01', name: 'John' }, { id: '02', name: 'Alice' }, { id: '03', name: 'Hana' }, { id: '04', name: 'Zoo' }, { id: '05', name: 'Sea' }]
 
Expected result:
[{ id: '02', name: 'Alice' }, { id: '03', name: 'Hana' }, { id: '01', name: 'John' }, {id: '05', name: 'Sea'}, { id: '04', name: 'Zoo' }]
 
Source code:

export type UserInfo = {
  id: string;
  name: string;
}
export type ApiResponse = {
  userInfo?: UserInfo[];
}
export const sortArray = (rootArr: ApiResponse) => {
  const resultArr: UserInfo[] = rootArr.userInfo ? rootArr.userInfo : [];
  return resultArr.sort((a, b) => {
    return a.name.localeCompare(b.name);
  })
}

Actual result:
TypeError: Cannot assign to read only property '0' of object '[object Array]' 
 
The reason behind it could be the array being in strict mode.
To solve this, you can duplicate of the array using various methods available.
 
Solution 1:
[...resultArr].sort((a, b) => {
return a.name.localeCompare(b.name);
});
 
Solution 2:
resultArr.slice().sort(((a, b) => {
return a.name.localeCompare(b.name);
});
 
Solution 3:
resultArr.map(item => item).sort(((a, b) => {
return a.name.localeCompare(b.name); });
});
 
Solution 4:
resultArr.concat([]).sort(((a, b) => {
return a.name.localeCompare(b.name);
});
 
Solution 5:
resultArr.filter(() => true).sort(((a, b) => {
return a.name.localeCompare(b.name);
});
 
Solution 6:
Array.from(resultArr).sort(((a, b) => {
return a.name.localeCompare(b.name);
});
 
Solution 7:
const resultArr: UserInfo[] = [];
(rootData.userInfo || []).forEach(item => { return resultArr.push(item)})
return resultArr.sort((a, b) => {
return a.name.localeCompare(b.name);
})
 
Bug Icon Transparent PNG Image

 Number string array sorting

The localeCompare() function is frequently used for comparing string data.

But in this case, number properties will be sorted as strings. It doesn't look at those strings as representing numbers.
 
Example: Sort float number string array in ascending order by number value
 
Input array:
[ ’12.12’, ‘8’, ’50.006’, ’32.21’, ‘1.002’ ]
 
Expected result:
[ ‘1.002’, ‘8’, ’12.12’, ’32.21’, ’50.006’ ]
 
Source code:

resultArr.sort((a, b) => {

return a.localeCompare(b);
});
 
Actual result:
[ ‘1.002’, ’12.12’, ’32.21’, ‘50.006’, ‘8’ ]
 
To solve this bug, we must replace localeCompare() function by converting number string data to numbers before comparing.
 
Solution 1:
resultArr.sort((a, b) => Number(a) – Number(b))
 
Solution 2:
resultArr.sort((a, b) => parseFloat(a) – parseFloat(b))
 
Conclusion

In general, we can sort an array of objects using Array.sort() and a custom comparison function. In there, we must define how our sort will function, or simply the sorting mechanism. Sorting is based on the value of the property that each object contains. Therefore, it is critical to identify the data type and its associated comparison function.
I hope this information is useful to you.

 
Refers:
Written by
Author Avatar
Engineering Core
ISB Vietnam's skilled software engineers deliver high-quality applications, leveraging their extensive experience in developing financial tools, business management systems, medical technology, and mobile/web platforms.

COMPANY PROFILE

Please check out our Company Profile.

Download

COMPANY PORTFOLIO

Explore my work!

Download

ASK ISB Vietnam ABOUT DEVELOPMENT

Let's talk about your project!

Contact US