prettier-plugin-sort-json
prettier-plugin-sort-json copied to clipboard
Allow sorting of arrays
This would be disabled by default obviously, since in many circumstances it would cause breaking changes.
By default, JavaScript calling Array.sort() on an array has odd behavior. Notably, objects will not have fully defined behavior and numbers will be sorted as strings (!!!).
Thus, my suggestion is that this functionality be added as part of #27, which will allow users to specify the sorting algorithm used for arrays, separately from object keys. If no sorting algorithm is specified for arrays, it can be assumed that the user does not want JavaScript's default confusing sorting behavior, and sorting of arrays will be disabled.
Hah, I was guessing that someone would ask for this! This would be a good feature, as long as it was opt-in, as you suggested.
It would absolutely have to be opt-in, because for many cases (but not all, hence the reason for this issue) the order of the elements in a JSON array is significant. Having it as an option would be convenient, though.
One issue is that in some cases you do not know which array you are sorting. With #27 providing a JavaScript function, the user could check for the type of the items being sorted before sorting. Alternatively, we could provide a third function parameter which provides the path of the variable being sorted.