paul_ngc paul_ngc - 1 month ago 11
Javascript Question

Shuffle Array with a fixed position as exception

I have an array that outputs several IDs. The order should be shuffled, but the first ID should stay at this position.
I’ve looked at the Fisher-Yates (aka Knuth) Shuffle, but I’m not sure how to edit it for my case.

One way could be to split it in two arrays. One with the single object. And then just shuffle the array with the other post. After the shuffling I combine the two arrays as I did in this fiddle: https://jsfiddle.net/464fmfty/2/

// array listing post ids
var arr = [2, 11, 37, 42, 88, 234, 23, 71, 172, 82];
var arrNew = [];

arrNew.push(arr.shift());
arr = shuffle(arr);
arrNew.push(arr);

document.body.innerHTML= arrNew;


But I was wondering if there is a better / more beautiful way to do this?

Answer

The shuffle function should be called like shuffle(arr, start, length), then the code becomes simple.

function shuffle(array, start, length) {
  var currentIndex, i, tmp, randomIndex;

   for (i = length; i > 1; i--) {

    // Pick a remaining element...
    randomIndex = start + Math.floor(Math.random() * i);
    currentIndex = start + i - 1;

    // And swap it with the current element.
    tmp = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = tmp;
  }
}

// array listing post ids
var arr = [2, 11, 37, 42, 88, 234, 23, 71, 172, 82];

shuffle(arr, 1, arr.length - 1);

document.body.innerHTML= arr;

Note that I removed the return arr, since it is confusing when a function modifies the array in-place and returns it.

Comments