0

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.

2 Answers 2

3

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
  );
});
Sign up to request clarification or add additional context in comments.

Comments

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:

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

// and then sort it like before

1 Comment

Might be useful to give alternative of filter for EcmaScript < 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.