Issue
I have a column in my table that displays file sizes in bytes, which isn't very easy to read. I've created a function that displays the sizes nicely in KB, MB, etc., but this messes up the sorting. I'm trying to figure out how to reconcile the two so the column displays the human-readable sizes but still sorts properly based on the raw size values.
Resolution
The problem is that sorting a column of file sizes displayed in a human-readable format is not reliable because the sorting will treat the file sizes as text instead of a number. The solution is to turn off table sorting and use lodash _.orderBy() to keep the data sorted by the raw size, while only displaying the human-readable version.
Here's an example of how to implement this solution:
Assuming that you have a column of file sizes in bytes and a function that converts bytes to a human-readable format, you can use the following code to display the human-readable version and sort the data by the raw size:
import _ from 'lodash'
function formatFileSize(bytes) {
// your function that converts bytes to a human-readable format
}
// your array of objects with a 'rawSize' property
const files = [
{ name: 'file1', rawSize: 1024 },
{ name: 'file2', rawSize: 2048 },
{ name: 'file3', rawSize: 512 },
]
// sort the data by the raw size using lodash _.orderBy()
const sortedFiles = _.orderBy(files, ['rawSize'], ['asc'])
// display the human-readable version in the UI
sortedFiles.forEach(file => {
console.log(`${file.name}: ${formatFileSize(file.rawSize)}`)
})
In this example, we first sort the data by the raw size using lodash _.orderBy(). The first argument is the array of objects we want to sort, and the second argument is an array of properties to sort by. We only have one property to sort by, so we pass in an array with just 'rawSize'. The third argument is an array of sorting orders, which in this case is just 'asc' (ascending). The function returns a new array with the same objects sorted by the raw size.
Then, we use a forEach loop to display the human-readable version in the UI using the formatFileSize() function. This way, the data is sorted by the raw size, but displayed in a more readable format.