Fadi
Fadi

Reputation: 2370

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.

Upvotes: 0

Views: 51

Answers (2)

Juank
Juank

Reputation: 6196

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:

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

// and then sort it like before

Upvotes: 0

Guffa
Guffa

Reputation: 700182

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

Upvotes: 3

Related Questions