I have got an array that contains data in hierarchical form such as:
Level 2
chapter 1
chapter 2
Level 4
chapter 1
chapter 2
Level 1
chapter 1
chapter 2
Level 3
chapter 1
chapter 2
If I just call array.sort(), the hierarchy gets disturbed. So, I have to develop my own way of sorting items. The thing I can’t understand is, how would I compare two levels such that I would know that level 1 is less than level 2 and it should be at the top index of the array?
You really shouldn’t be using a flat array. You lose all the hierarchical information. Something like this would be better:
EDIT
Rob suggested using
levels.sort(function(x,y){return x.localeCompare(y)})instead of the regular.sort(). The former will sort["abc", "Abcd", "Ab"]to["Ab", "abc", "Abcd"]instead of["Ab", "Abcd", "abc"].