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
})
2
  • What's problem? Commented Oct 25, 2016 at 17:39
  • The filenames are strings, and are sorted alphanumerically. If you named the files 00, 01, 02, 03, etc it would sort as you want. Commented Oct 25, 2016 at 17:54

2 Answers 2

3

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That topic in this site solves the problem.
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.

1 Comment

Should be return parseInt(a) > parseInt(b) ? 1 : -1; but it works well, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.