2014-12-02 77 views
1

您好我有對象如何排序對象數組基座上的兩個屬性

cards = [ 
{ Asset: "2C.jpg", 
    CardName: "2C", 
    CardPlayed: 0, 
    Playbell: 0, 
    PlayerName: "player1", 
    Rank: 2, 
    Suit: "C" 
}, 
{ Asset: "9S.jpg", 
    CardName: "9S", 
    CardPlayed: 0, 
    Playbell: 0, 
    PlayerName: "player2", 
    Rank: 9, 
    Suit: "S" 
}, 
{ Asset: "6D.jpg", 
    CardName: "6D", 
    CardPlayed: 0, 
    Playbell: 0, 
    PlayerName: "player1", 
    Rank: 6, 
    Suit: "D" 
}]; 

的陣列,並且我需要上Suit屬性,但僅對於具有PlayerName屬性值等於物體排序這些對象基"player1"和許多提前感謝任何幫助。

回答

2

陣列上PlayerName排序,然後Suit

cards.sort(function(x, y){ 
    return (
    x.PlayerName < y.PlayerName ? -1 : 
    x.PlayerName > y.PlayerName ? 1 : 
    x.Suit < y.Suit ? -1 : 
    x.Suit > y.Suit ? 1 : 
    0 
); 
}); 
0
var filtered = cards.filter(function(card){ 
    return card.PlayerName === "player1"; 
}); 

var sorted = filtered.sort(function(a,b){ 
    if (a.Suit > b.Suit) { 
    return 1; 
    } 
    if (a.Suit < b.Suit) { 
    return -1; 
    } 
    // a must be equal to b 
    return 0; 
}); 

根據MDN過濾器不會對IE8的工作,下面,你可以使用填充工具上https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter的規定,或者你可以遍歷所有項目和手動篩選他們是這樣的:

var filtered = []; 
for (var i in cards){ 
    if (cards[i].PlayerName === "player1"){ 
     filtered.push(cards[i]); 
    } 
} 

// and then sort it like before 
+0

可能是,給出的EcmaScript <5濾波器的替代有用 – 2014-12-02 16:58:16

相關問題