Issue
I've been trying to map an array in a random way. I want every object of the array to show up. But the order should always be different and random on refresh.
const [ list ] = [
{id: 0, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 1, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 2, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 3, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 4, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 5, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 6, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 7, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 8, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 9, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false}
];
{list.map((item) => (...
Solution
I think it would be more useful to shuffle the array. And you should also change the definition of the constant.
You could try something like this:
const shuffle = arr => [...arr].sort(() => Math.random() - 0.5);
const list = [
{id: 0, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 1, img: "img", key: 0, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 2, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 3, img: "img", key: 2, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 4, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 5, img: "img", key: 3, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 6, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 7, img: "img", key: 4, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 8, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false},
{id: 9, img: "img", key: 5, class: "wrap", classFlip: "wrap card-flip", match: false}
];
const newList = shuffle(list);
console.log(newList);
Answered By - Niels Bosman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.