0

Total newbie so apologies if this is a silly question. I'm trying to write a function which takes an array of any length and randomises all the indices, apart from the first and last indices. So basically I want to remove the first and last indices and then shuffle the remaining indices and then reattach the removed indices back in their original place.

for example

var anyArray = ['ONE', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'TEN'];

and return something like

var anyArray = ['ONE', 'six', 'nine', 'four', 'eight', 'two', 'five', 'three', 'seven', 'TEN'];

n2kp
  • 3
  • 1
  • Looks like you can get help from some of these other questions: http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array - Just keep track of your first and last element first... – pacifier21 May 20 '17 at 15:48

3 Answers3

0

First you need some shuffling algorithm. Taken from this answer https://stackoverflow.com/a/10142256/446792

Array.prototype.shuffle = function() {
  var i = this.length, j, temp;
  if ( i == 0 ) return this;
  while ( --i ) {
     j = Math.floor( Math.random() * ( i + 1 ) );
     temp = this[i];
     this[i] = this[j];
     this[j] = temp;
  }
  return this;
}

Then save first and last element, sort array, restore first and last element.

var anyArray = ['ONE', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'TEN'];

var first = anyArray.shift()
var last = anyArray.pop()

anyArray.shuffle()

anyArray.unshift(first)
anyArray.push(last)
Community
  • 1
  • 1
mx0
  • 6,445
  • 12
  • 49
  • 54
0

Like in the comment, check out the shuffling algorithm. To your need to extract only those in the middle and then reattach, try following

let inner = anyArray.splice(1, anyArray.length-2)
shuffle(inner)
inner.unshift(anyArray[0]);
inner.push(anyArray[1]);
Luke
  • 8,235
  • 3
  • 22
  • 36
0

Array#sort() accepts a callback as the first parameter so you can tell the program how to sort your Array, you can use that to shuffle the Array.

This function does what you want:

Array.prototype.shuffleLeaveFL = function() {
  var arr = [];
  for(let i=1; i<this.length-1; i++){ arr.push(this[i]); }
  arr.sort(function() { return 0.5 - Math.random() }); // shuffle array
  arr.push(this[this.length-1]); // add old last element to arr
  arr.unshift(this[0]); // add old first element to front of arr
  return arr;
}

var array = ["FIRST", "two","three","four","five","six","seven","eight","nine", "LAST"];

// simply use this on any Array

console.log(array.shuffleLeaveFL());

Sort method taken from CSS-Tricks

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44