I'm trying to shift the values of an array over by a random number. Example:
var array = [1,2,3,4];
var shiftAmount = 1;
I want to shift it over so that it would be [4,1,2,3]
I'm trying to shift the values of an array over by a random number. Example:
var array = [1,2,3,4];
var shiftAmount = 1;
I want to shift it over so that it would be [4,1,2,3]
Just split the array with slice and concat it afterwards contrariwise. Shift had to be calculated with modulo array-length so you can shift for any number.
For getting a random-number use Math.random() and round it with Math.round. Because random delievers values between 0 and 1 you have to multiply it with arraylength -1 (because index count from 0 to length -1).
function shiftArray(arr,shift) {
shift = shift % array.length;
return arr.slice(shift).concat(arr.slice(0,shift));
}
var array = [1,2,3,4];
let shift = Math.round(Math.random() * (array.length-1));
let result = shiftArray(array, shift);
console.log('Shift by ' + shift + ': ',result.toString());