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:
| Object array sorting |
But if the array has 2+ items, attempting to sort it will cause a TypeError.
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);
})
}
| TypeError: Cannot assign to read only property '0' of object '[object Array]' |
To solve this, you can duplicate of the array using various methods available.
[...resultArr].sort((a, b) => {return a.name.localeCompare(b.name);});resultArr.slice().sort(((a, b) => {return a.name.localeCompare(b.name);});resultArr.map(item => item).sort(((a, b) => {return a.name.localeCompare(b.name); });});resultArr.concat([]).sort(((a, b) => {return a.name.localeCompare(b.name);});resultArr.filter(() => true).sort(((a, b) => {return a.name.localeCompare(b.name);});Array.from(resultArr).sort(((a, b) => {return a.name.localeCompare(b.name);});const resultArr: UserInfo[] = [];(rootData.userInfo || []).forEach(item => { return resultArr.push(item)})return resultArr.sort((a, b) => {return a.name.localeCompare(b.name);})
Number string array sorting |
The localeCompare() function is frequently used for comparing string data.
resultArr.sort((a, b) => {
return a.localeCompare(b);});localeCompare() function by converting number string data to numbers before comparing.resultArr.sort((a, b) => Number(a) – Number(b))resultArr.sort((a, b) => parseFloat(a) – parseFloat(b))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.
- https://copyprogramming.com/howto/how-to-solve-a-problem-with-array-sort-cannot-assign-to-read-only-property-0-of-object
- https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/
- https://www.freepik.com/free-vector/gradient-futuristic-background_18954473.htm#from_view=detail_alsolike (Image source)
- https://freepngimg.com/png/31420-bug-icon-transparent (Image source)