Need help to randomize repeater

I have testimonials which I want to show on my site, 4 of them out of a list of 13. I used this code from a different discussion which works partly.
https://www.wix.com/corvid/forum/community-discussion/can-we-randomize-database-info-in-a-repeating-layout

import wixData from 'wix-data';

$w.onReady(function () {
 //get the collection records
  wixData.query("Testimonials")
    .limit(4)
    .find()
    .then((result) => {
 const shuffledArray = shuffleArray(result.items);
 //add the shuffled array data to then repeaters
      $w('#repeater1').data = shuffledArray;      
    })
    .catch((err) => {
 let errorMsg = err;
    });
});

//random array index
function getRandomIndex(min, max) {
 return Math.round(Math.random() * (max - min) + min);
}

//shuffle array data
function shuffleArray(dataArray){

 for(let i = dataArray.length - 1; i > 0; i--){
 let index = getRandomIndex(0, i);
 const temp = dataArray[i];
    dataArray[i] = dataArray[index];
    dataArray[index] = temp;
  }
 
 return dataArray;
}

I set the limit to 4 and it does shuffle the testimonials, but it only uses the same 4 ones over and over again. What am I doing wrong?

Thank you in advance for your help!!

You only pulled 4 items from the database (" . limit ( 4 ) ") based on the default order .
You need to remove the limit.
and after you shuffle the full array use the first 4:

return dataArray.slice(0,4);

Hi Thanks for the quick response, I’m not sure I put it in the right place. It’s showing all testimonials rather than 4 right now.

//shuffle array data
function shuffleArray(dataArray){
 for(let i = dataArray.length - 1; i > 0; i--){
 let index = getRandomIndex(0, i);
 const temp = dataArray[i];
    dataArray[i] = dataArray[index];
    dataArray[index] = temp;
    const toDisplay = dataArray.slice(0,4);
  }
 return dataArray;
}

I made it shorter:
delete:

const toDisplay = dataArray.slice(0,4);

And write:

return dataArray.slice(0,4);
//instead of the "return dataArray;'

J.D. That did the trick I think, thanks so much!!!

Hi all - also trying to randomize a repeater. I’m by no means an expert with coding so I would love some help. I have a data set called teamRepeater. I just was it to shuffle on each page load. There are a lot of items in the data set. I used the code above and tried changing it - but I am getting the error that teamRepeater collection does not exist? I disconnected the data set then reconnected.

Can anyone help?

The code above is not for data set s, but for direct collection queries.

Is there a way to code this for data sets then?