1

I have some arrays and want to randomise them using shuffle (as explained here)

However, I want all my arrays to be concatenated into one big array and them go through the array one by one.

Now I noticed that neither this:

var proxies =   [
        {stim: A},
        {stim: B},
        {stim: C},
        {stim: D}]
var a = shuffle(proxies); var b = shuffle(proxies); var c = shuffle(proxies);
var x = a.concat(b, c)

nor that:

var x = shuffle(proxies).concat(shuffle(proxies), shuffle(proxies)) 

does produce a larger array which is composed of three different shuffled orders of my initial proxies array.

If I log to console, I see that for both options it always one shuffled order repeated three times. It seems as if it is shuffled only once and then remains in that order.

Ideas about fixing this?

Community
  • 1
  • 1
ben_aaron
  • 1,504
  • 2
  • 19
  • 39

2 Answers2

1

If you want to use the function of the post that you mentioned in your question, you must modify it slightly. And your code will be

<script type="text/javascript">
    function shuffle(array) {
      var newarr=[]
      var currentIndex = array.length,
         temporaryValue,
         randomIndex;
      while (0 !== currentIndex) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        newarr[currentIndex] = array[randomIndex]
        array[randomIndex] = temporaryValue;

      }

      return newarr;
    }

    var proxies =   [{stim:'a'},{stim: 'b'},{stim: 'c'},{stim: 'd'}]
    var a=shuffle(proxies);
    var b=shuffle(proxies);
    var c=shuffle(proxies);
    var x=a.concat(b, c)
    console.log(x)
</script>
Devima
  • 1,566
  • 2
  • 10
  • 16
0

It appears as though your shuffle() function is acting on the given array, and not producing a new one. So in your first example, a, b, and c are all equal to the same array.

If you want to create 3 unique shuffles, then you must clone/copy the array prior to shuffling and concatenating. Plenty of options for that, eg: How do you clone an Array of Objects in Javascript?

Community
  • 1
  • 1
Matt Way
  • 32,319
  • 10
  • 79
  • 85