简体   繁体   English

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

[英]How to sort array objects base on two properties

Hi i have an array of objects 嗨,我有一系列对象

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"
}];

and i need to sort those objects base on Suit property but only for the object that have the PlayerName property value equal to "player1" and many thanks in advance for any help. 我需要基于Suit属性对这些对象进行排序,但仅针对PlayerName属性值等于"player1"的对象,并在此先感谢您的帮助。

To sort the array on PlayerName and then Suit : 要对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
  );
});
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;
});

According to MDN filter doesn't work on ie8 and below, you could use a polyfill as stated on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter , or you could iterate over all items and filter them manually like this: 根据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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM