B
B
ByJumping2022-02-20 01:43:14
JavaScript
ByJumping, 2022-02-20 01:43:14

How to randomly shuffle the elements of an object?

I display images using v-for

<div v-for="(image,i) in images" class="game__wrapper_item" :key="i" @click="showCard(image, i)">
        <img :src="image.path" alt=""/>
      </div>


There is an array of images objects

export const imagesData = [
    {id: 1, path:  require('./img/image1.jpg')},
    {id: 2, path:  require('./img/image2.jpg')},
    {id: 3, path:  require('./img/image3.jpg')},
    {id: 4, path:  require('./img/image4.jpg')},
    {id: 5, path:  require('./img/image5.jpg')},
    {id: 1, path:  require('./img/image1.jpg')},
    {id: 2, path:  require('./img/image2.jpg')},
    {id: 3, path:  require('./img/image3.jpg')},
    {id: 4, path:  require('./img/image4.jpg')},
    {id: 5, path:  require('./img/image5.jpg')},
]


To shuffle a regular array I use the function
randomItem (items) {
      return items[Math.floor(Math.random()*items.length)];
    }

I need to draw pictures randomly, but their id should remain the same.
But I can’t figure out how to mix the elements of an object, but so that the id remains unchanged.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-02-20
@ByJumping

function shuffle(arr) {
    for (let i = arr.length - 1; i > 0; --i) {
        const pos = Math.floor(Math.random() * (i + 1));
        const t = arr[pos];
        arr[pos] = arr[i];
        arr[i] = t;
    }
    return arr;
}

const newArr = shuffle(imagesData.slice()); // новый перемешанный, imagesData не поменялось
const newArr2 = shuffle(imagesData); // перемешали imagesData, присвоили в newArr2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question