Hi!
i’m a beginner who’s working on a Memory Game for practice, mixing different ways trying to build it for learning, mainly from the freecodecamp tutorial and I got to the last part of shuffling and they put this code:
function shuffle() {
cards.forEach(card => {
let ramdomPos = Math.floor(Math.random() * 12);
card.style.order = ramdomPos;
});
}
it works for them differently from me, for me, it gives the same order number to all cards while for them it gives different numbers to each card (both made in div, and both been taken out from HTML with quarySelectorAll)
until this part, everything worked well but now it’s just not.
if you have an idea of what to check ill be happy to hear!
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
It’s also not clear to me how this changes the order. So, cards is an array. Why does adding a “style.order” prop change that? Unless you have something using that value somewhere else?
Also, since there are only 12 possible positions, what happens if it returns the same position value more than once. This seems like a poor way to shuffle. I suppose an approach like that could work if you use floating points for the positions. But this is not shuffling, just giving some random numbers to a prop.
I usually just use the Fisher-Yates shuffle algorithm. This would actually shuffle those elements in that array.
I think I’d have to know more about what those objects are and what you hope to accomplish.
I had the same thoughts but my guess is that the cards are in a flex- or grid-container. If two order values end up being identical, they’d get added to the container next to each other. I think for a tutorial, that’s random-ish enough.
If you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.
The order property doesn’t work unless the element is a flex or grid child. You have to make the parent element a flex/grid container (i.e. the .row element in your case). The way you have it set up with row containers might also not work as well as having one common container for all the children, but I’m guessing it will work well enough.