-1

I am trying to combine two two arrays to make a full deck of cards that looks like so:

[{card: "A", suit: "d"}, {card: "A", suit: "c"}, {card: "A", suit: "s"},    {card: "A", suit: "h"}, {card: "2", suit: "d"}.....]

.... this is what I have so far:

function newDeck(ranks, suits){
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

var suits = ["d", "c", "s", "h"]

var deck= []

  for (i = 0; i < suits.length; i++) {

  for (j = 0; j < ranks.length; j++) {

      this.deck[ranks.length*i+j] = new Card(ranks[j], suits[i]);
  }
} console.log(newDeck)
}
Crystal
  • 1,425
  • 1
  • 22
  • 34
  • try not to edit your question too much as it makes it difficult for people to make sense of the answers posted prior to the edit. Instead just add additional information below the original post :) – GregH Jul 20 '15 at 22:16
  • http://stackoverflow.com/questions/4331092/finding-all-combinations-of-javascript-array-values – ThatOneDude Jul 20 '15 at 22:16

2 Answers2

1

Using Array.forEach you can do the following:

var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["d", "c", "s", "h"];
var deck= [];
suits.forEach(function(suit){
  ranks.forEach(function(rank){
    deck.push(new Card(rank, suit));
  })
});

EDIT: and in case you haven't written the Card method yet:

function Card(rank, suit){
  this.card = rank;
  this.suit = suit;
}
Michele Ricciardi
  • 2,107
  • 14
  • 17
0

If you combine the two arrays you will have an array:

["A","2","3","4","5","6","7","8","9","10","J","Q","K","d","c","s","h"]

which does not represent a full deck of card, whereas using an embedded for loop to print out card as you are now will so I don't think you just want to append one array to the other. Can you provide more context on what you want to do with the array?

However, to answer your question: if you want to append two arrays you can use:

var appendedArray = ranks.concat(suits);

which will result in the aforementioned array above

pertaining to your updated question: you are called "new Card(ranks[j], suits[i]);" have you made a Card constructor so that this is valid? if so, the code should be correct if the constructor matches how you are using it. Posting the code for the constructor would be helpful along with an update of what issue you are facing

GregH
  • 5,125
  • 8
  • 55
  • 109
  • 1
    Yes I am trying to loop through both arrays to create value pairs representing a full deck of cards like this: [{card: "A", suit: "d"}, {card: "A", suit: "c"}, {card: "A", suit: "s"}, {card: "A", suit: "h"}, {card: "2", suit: "d"}.....] – Crystal Jul 20 '15 at 22:11
  • if that is the case then take a look at: http://www.brainjar.com/js/cards/ which has an pretty spot on example for you. In short, you need to be creating a card object via a constructor to represent a card. If you found this information helpful please upvote/accept – GregH Jul 20 '15 at 22:13