0

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
})
Nasuh
  • 355
  • 3
  • 20

2 Answers2

2

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:

Community
  • 1
  • 1
Ding
  • 3,065
  • 1
  • 16
  • 27
0

Problem in here will be in file names that has letter in it. But from your example since node already sorted 00Letter in correct order, I have simple solution like this

var a = ["10.jpg", "00a.jpg", "5.jpg", "00c.jpg", "3.jpg", "00b.jpg"];

var b = a.sort(function(a,b) {
  return parseInt(a) > parseInt(b);
});

console.log(b);
//output 
["00a.jpg", "00c.jpg", "00b.jpg", "3.jpg", "5.jpg", "10.jpg"]

UPDATE As @Ding mentioned. Better to create custom function that captures everything and not hoping on node sort too.

Hope this helps.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24