Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array in nodejs based on file size?

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?

like image 365
Harkirat Saluja Avatar asked Jan 11 '16 07:01

Harkirat Saluja


People also ask

How do you sort an array by size?

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.

How do you sort an array in node JS?

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.

How do you sort an array from smallest to largest?

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.


2 Answers

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.

like image 50
Michał Perłakowski Avatar answered Sep 18 '22 07:09

Michał Perłakowski


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);
like image 34
Shanoor Avatar answered Sep 19 '22 07:09

Shanoor