开发者

sorting selected items in an array (javascript)

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 开发者_C百科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:

//I've deliberately made these unsorted to show you that sorting works
levels = ["Level 4", "Level 3", "Level 1", "Level 2"];

data = {
  "Level 3" : ["chapter 1", "chapter 2"],
  "Level 1" : ["chapter 2", "chapter 1"],
  "Level 2" : ["chapter 2", "chapter 1"],
  "Level 4" : ["chapter 1", "chapter 2"]  
};

levels.sort();
for(var i = 0 i < levels.length; i++) {
    console.log(levels[i]);
    var chapters = data[levels[i]];

    chapters.sort();    
    for(var j = 0; j < chapters.length; j++) {
        console.log(chapters[j]);
    }
}

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"].


This should reformat the flat PHP array to the nicer JS object:

var fromPHP = ['Level 2','chapter 1','chapter 2','Level 4','chapter 1','chapter 2','Level 1','chapter 1','chapter 2','Level 3','chapter 1','chapter 2'];

var levels = [],
    betterArray = [fromPHP[0]],
    currentLevel=betterArray[0];

for (var i=1;i<fromPHP.length;i++) {
  if (fromPHP[i].substr(0,5) == 'Level') {
    currentLevel = [];
    levels.push(fromPHP[i]);
    betterArray[fromPHP[i]] = currentLevel;
  } else {
    currentLevel.push(fromPHP[i]);
  }
}

Should give the following levels and betterArray:

// levels:
['Level 4','Level 3','Level 1','Level 2']

// betterArray:
{
    'Level 2': ['chapter 1','chapter 2'],
    'Level 4': ['chapter 1','chapter 2'],
    'Level 1': ['chapter 1','chapter 2'],
    'Level 3': ['chapter 1','chapter 2']
}

Now you can run whatever sorting you want on the subarrays and get what you wanted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜