如何基于两个属性对数组对象进行排序

时间:2014-12-02 16:50:03

标签: javascript

嗨,我有一个对象数组

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"的对象,并提前感谢任何帮助。< / p>

2 个答案:

答案 0 :(得分: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
  );
});

答案 1 :(得分: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中所述的polyfill,或者您可以迭代所有项目并手动过滤它们:

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

// and then sort it like before