2014-05-03 179 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

完美。正是我想要的 –