Nasuh Nasuh - 1 month ago 16
Node.js Question

Nodejs filesystem array sort numeric

MY nodejs app reading some image files. But its sorting it alphabetically.

On the left side what Nodejs got and on the right side what should it looks like.

enter image description here
enter image description here

And my Nodejs code is:

var files = fs.readdirSync('./public/manga/' + req.params.name).map(function(item){
var subfolders = fs.readdirSync('./public/manga/' + req.params.name + '/' + item);
return {
chapter: item,
paths: subfolders.map(function (i) {
return "manga/" + req.params.name + "/" + item + "/" + i;
})
}
})
res.json(files);
});


What I try and and didnt work.

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){ //Array now becomes [7, 8, 25, 41]
return a - b
})

Answer

You're looking for the natural sort order. There are lots of examples out there.

There's a good npm module for it https://github.com/Bill4Time/javascript-natural-sort.

You can also implement a quick function and there are lots of good examples:

Comments