0

What I try is to check the state.newCardArray and remove that item based on index and then push it to state.arrayFoldedCards. This is a card game, so if the newCardArray is empty and there is no winner or loser, then the game stops....

const initialState = {
  newCardArray: ['a', 'b', 'c']; // after removing the array looks like ['a', 'c']
  arrayFoldedCards: [] // pushing to the array resulted in an updated array that looks like ['b']
}

export const game = (state = initialState, action) => {
  switch (action.type) {
    case types.GET_CARD:
      {
        const getRandomNumber = Math.floor(state.newCardArray.length * Math.random());
        console.log(state.newCardArray);
        console.log(state.arrayFoldedCards);
        return {
          ...state,
          randomNumber: getRandomNumber,
          arrayFoldedCards: state.newCardArray[getRandomNumber].push(state.arrayFoldedCards.pop())
        }
      }
  }
}
2
  • newCardArray[getRandomNumber] will give you an element from the array calling newCardArray[getRandomNumber].push() means you expect that element to be an array and you want to add an item to the sub-array. Since you have plain strings, that's not going to work. Commented Dec 17, 2019 at 13:12
  • Yes that is why I post my code here...i knew this was not the right way to do that. Please check the out commented text to understand the array. Commented Dec 17, 2019 at 13:13

2 Answers 2

3

Looks like you want something like splice/concat

var idxToRemove = 1; //Removing 'b'
var arr0 = ['a', 'b', 'c']; 
var arr1 = []; //Array to move to

return arr1.concat(arr0.splice(idxToRemove, 1));

Splice returns an array of removed elements so you can concat them together. Concat merges the two arrays without mutating either.

Sign up to request clarification or add additional context in comments.

1 Comment

Splice mutates arr0 in the process, so two birds with one stone. Nice.
0

case types.GET_CARD: {
    const indexToRemove = Math.floor(state.currentCardArray.length * Math.random());
    const updatedArray = state.arrayFoldedCards.concat(state.currentCardArray.splice(indexToRemove, 1));

    return {
        ...state,
        arrayFoldedCards: updatedArray
    }
}

Comments

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.