-2

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]

Iridium
  • 23
  • 1
  • 1
    OK so you told us what you would like to do but haven't shown us any attempts to solve it to show us where you are stuck. There are numerous ways to accomplish this...show us what you have tried. See [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – charlietfl Aug 16 '20 at 02:08

1 Answers1

-1

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());
Sascha
  • 4,416
  • 3
  • 11
  • 33