I have an array with names of files as the entities of the array. I wanted to sort this array based on the size of the files.
For example,
var arr=['index.html','README.md','index.html'];
So what I currently have is that I create an object with name of files as key and size of file as the value.
Now I am fetching these files from a remote location, so I can get the size of the file from content-length
header.
Is there a better way to do it? Will it be possible to do this locally by which I mean read file size and create an object based on that?
To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.
Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
Try this:
var arr = ['index.html','README.md','index.html'];
arr.sort(function(a, b) {
return fs.statSync(a).size - fs.statSync(b).size;
});
I assume that these files are in your current directory.
Short memoized version without promises:
var arr = ['index.html', 'README.md', 'index.html'];
var sortedArray = arr
// get the size of each file
.map(file => { return { file: file, size: fs.statSync(file).size } })
// sort by size ascending
.sort((a, b) => a.size > b.size)
// return a simple sorted array of the file names only
.map(f => f.file);
console.log(sortedArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With