0

So I am trying to merge two arrays into one object. More specifically I am creating a deck of cards using JavaScript. I have created the two arrays (shown below) and am looking for some help on how to merge them so that the new object will be formatted like this {suit: 'hearts', value: 'A'}. I believe i need to do a for loop but haven't been able to make it work. Anyone have any suggestions?

// ... trying to merge the two arrays here ...

  function deck_o_cards() {
  var values = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'];
  var suits = ['hearts', 'diamonds', 'clubs', 'spades'];

  var cards = [ ];
    for(i=0, i< suits.length, i++){
        var newSuit = suits[i];
        for(a=0; a< values.length, a++) {
            var newValue= values[a];
            newArray=[newSuit, newValue];
            cards.push(newArray);
        }
    }
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Matt
  • 13
  • 4
  • A loop is a good start, can you show us what you tried? By the way is it a homework? If it is, it's always good to specify it as part of your text so people can guide you better. – Gabriel GM May 04 '15 at 23:46
  • Do you have a problem with the loop code you've added? Did you want a [multidimensional array](http://stackoverflow.com/questions/7545641)? – Dave Anderson May 05 '15 at 00:14
  • Thanks for all the help everyone. It was a homework problem. I have been able to get it to create the deck now. Thanks again – Matt May 05 '15 at 15:31

2 Answers2

1

You will need to iterate over the values array using a loop and then inside each iteration also iterate over the suits array in a loop. You will need two different indexes to make the nested loops work.

The arrays are zero indexed so the index will begin at zero and stop when it index reaches the length of the array.

Here is an example of a nested loop but you should use the array length property rather than 13 and 4.

for(var i = 0; i < 13; i++) {
  for(var j = 0; i < 4; i++) {
    ...
  }
}

Inside the inner loop you can create your card object with the value from each array using the separate indexes and add it to your card array by assigning it to cards[cards.length] = { } which adds a new item to the end of the array.

You can also accomplish the same thing using the Array.map() and Array.push() functions to replace the loop and assignment operations.

Community
  • 1
  • 1
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
0

You are almost there. The problem lies with the code inside your loop. You are creating an array when you actually desire an object. Try this inside your loop:

var newValue = values[a];
var newCard = {suit: newSuit, value: newValue};
cards.push(newCard);

Also note the use of var newCard instead of newArray. var avoids adding an object to the global scope.

datchung
  • 3,778
  • 1
  • 28
  • 29