-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]

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? Commented Aug 16, 2020 at 2:08

1 Answer 1

-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());

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.