2014-05-03 131 views
1

我已经搜索过但我找不到JavaScript/jQuery解决方案。 我有对象的这样在javascript对象数组中进行排序和排序

MLDS = [ 
    {"Group": "Red","Level": "Level 2"}, 
    {"Group": "Green","Level": "Level 1"}, 
    {"Group": "Red","Level": "Level 1"}, 
    {"Group": "Blue","Level": "Level 1"}, 
    {"Group": "Green","Level": "Level 2"}, 
    {"Group": "Yellow","Level": "Level 1"} 
    ] 

我希望能够重组的集团与等级对应的组排序中返回的对象的另一个数组中的新秩序阵列,使得

MLDS = [ 
    {"Group": "Red","Level": "Level 1"}, 
    {"Group": "Red","Level": "Level 2"}, 
    {"Group": "Green","Level": "Level 1"}, 
    {"Group": "Green","Level": "Level 2"}, 
    {"Group": "Blue","Level": "Level 1"}, 
    {"Group": "Yellow","Level": "Level 1"} 
    ] 

我需要能够保持组的顺序,他们第一次出现,所以我需要,在这种情况下,维持红色,绿色,蓝色然后黄组排序,但排序在这些组

回答

3

首先你需要遍历数组一次牛逼起来将包含组的顺序,因为这是要保持一个数组:

// this will hold the unique groups that have been found 
var groupOrder = []; 

// iterate through the array, 
// when a new group is found, add it to the groupOrder 
for (var i = 0; i < MLDS.length; i++) { 
    // this checks that the current item's group is not yet in groupOrder 
    // since an index of -1 means 'not found' 
    if (groupOrder.indexOf(MLDS[i].Group) === -1) { 
    // add this group to groupOrder 
    groupOrder.push(MLDS[i].Group); 
    } 
} 

然后你就可以使用排序功能,首先排序由什么指标项目的Group有在groupOrder,然后,如果他们有相同的组,只需按Level排序:

MLDS.sort(function(a, b) { 
    if (groupOrder.indexOf(a.Group) < groupOrder.indexOf(b.Group)) { 
    return -1; 
    } else if (groupOrder.indexOf(a.Group) > groupOrder.indexOf(b.Group)) { 
    return 1; 
    } else if (a.Level < b.Level) { 
    return -1; 
    } else if (a.Level > b.Level) { 
    return 1; 
    } else { 
    return 0; 
    } 
}); 
+0

完美。正是我想要的 –