0

I've written some code that looks like:

state.intro = state.memoryCards[Math.floor(Math.random() * state.memoryCards.length)];

I don't think this is the right way to mutate the state, so I was refactoring the code below, but i am not sure how to return one index of that memoryCards array.


 intro: state.memoryCards.find(function(card, index) {
                    const randomIndex = Math.floor(Math.random() * state.memoryCards.length);
                    if(index === randomIndex) {
                        return card
                    }
                })
2
  • is this a redux reducer or is state the state of a React component? Commented Jun 24, 2019 at 21:22
  • Both are state inside a redux reducer Commented Jun 24, 2019 at 21:35

2 Answers 2

1

I think you mean

state.memoryCards.find(
    (card, index) => index === Math.floor(
        Math.random() * state.memoryCards.length
    )
).type

(but I'm not sure I understand what you want)

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

2 Comments

But is that good to have a math random method inside a reducer
yeah there's nothing wrong with using Math.random inside a reducer in principal, if you actually want that random choice put into the store, and that random choice needs to be accessed from various parts of the app. However, I think in most cases which require you to select a random element from state you would do that in a selector rather than a reducer.
0

In this case it comes down to what method you are looking to return from the array itself.

Map will return an array that is the same length as the one being looked over, Find as a method will return the first element that passes the input test for the array.

You had the proper spread on state, so that previous state is input into the return first, and then it overwrite memoryCards with the new one, and (I'm guessing...) inputs the rest of the memoryCards that are in that object, and overwrites the specific index with the next type value

Edit: return only one value for memoryCards

intro: state.memoryCards.find((card, index) => {
    const randomCard = Math.floor(Math.random() * state.memoryCards.length)
    if(index === randomCard) {
        return {
            ...state,
            memoryCards: card.type
        }
    }
})

2 Comments

but i want one value instead of the entire array.
I'll update my answer to only return a single value.

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.