Home > Mobile >  I wrote a function to merge two arrays into a single array but I'm getting "Cannot read pr
I wrote a function to merge two arrays into a single array but I'm getting "Cannot read pr

Time:02-23

I am trying to take 2 arrays and merge them into one new array that will combine the objects of each array. I understand how to combine 2 arrays into 1 large one, but I'm having trouble combining the actual objects into a new object within that array. An example of the input and intended output I am trying to get is listed below:

Given arrays:

array1 = ['1','2','3'];

array2 = ['a','b','c'];

New outputted array should be:

array3 = ['1a','2b','3c'];

Here is what i have attempted to do so far. In this example, I am trying to create the deck of cards needed to play a game of euchre (should have the cards 9, 10, Jack, Queen, and Ace and the suits of Clubs, Diamonds, Hearts, and Spades for each card for a total of 24 card combinations). I created 2 arrays (one for the card 'value' and one for the card 'suits.' For my function, I am passing both of these decks into a for loop that will ideally append the object of the 'suits' array to the end of the 'values' array. This new list is then passed into the empty 'deck' array to return the new array. However, I am getting and "Uncaught TypeError: Cannot read properties of undefined (reading 'length')." This is occuring at the beginning of my function 'createDeck' and when I try to call the function in the console log statement at the bottom. Any assistance in understanding the logic I would need to use to combine these arrays would be greatly appreciated as I am just beginning to work with functions and arrays.

const values = ['9','10', 'J', 'Q', 'K','A'];
const suits =  ['C', 'D', 'H', 'S'];

function createDeck(values, suits) {

  let deck = [];

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

    for (let x = 0; x < values.length; x  ) {

        let card = {Value: values[x], Suit: suits[i]};

        deck.push(card);
    }

}

  return deck;
}

console.log(createDeck());

CodePudding user response:

You can create a new array with the map method.

const values = ['1','2', '3'];
const suits =  ['a', 'b', 'c'];

function createDeck() {
  let customArray = [];
  
  // check for equality of array lengths
  if (values.length === suits.length) {
    // create a new array with the map method
    customArray = values.map((value, index) => {
      return value   suits[index]
    })
  }

  return customArray;
}

console.log(createDeck())

CodePudding user response:

try to declare a new array and in the for loop do

array[i] = values[i]   suits[i]

maybe you need to add "" in the array with strings

  • Related