Display 3 randomized item from a dataset

Question:
So I have this repeater which supposed to has 3 items in it (randomized). But using my code, it’s only displaying 1 items, how do I solve this?

Product:
Wix Editor

What are you trying to achieve:
Displaying 3 items instead of 1

What have you already tried:
Setting the dataset to display 3 items (by the dataset setting not by the code)

Additional information:
Here’s my code

import wixData from 'wix-data';

$w.onReady(function () {
    initiate();
});

function initiate() {
    wixData.query('Surabaya')
    .limit(100) //gets the maximum number of items allowed
    .find() //if you have database permissions then run this query on the backend
    .then( (results) => {
        let array = results.items;
        let random = shuffle(array); //shuffle data
        $w("#repeater4").data = [random[3]]; //set repeater data
    });
}

function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }
    return array;
}

Stackoverflow shows another way to shuffle this array and take a slice of n size from it:

// Shuffle array
const random = array.sort(() => 0.5 - Math.random());

// Get sub-array of first 3 elements after shuffled
$w("#repeater4").data = random.slice(0, 3);

Thanks a lot! It works

1 Like