Back to Freecodecamp

Challenge 95: Array Shift

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68f6587287ad1f4ad39b0c81.md

latest1.5 KB
Original Source

--description--

Given an array and an integer representing how many positions to shift the array, return the shifted array.

  • A positive integer shifts the array to the left.
  • A negative integer shifts the array to the right.
  • The shift wraps around the array.

For example, given [1, 2, 3] and 1, shift the array 1 to the left, returning [2, 3, 1].

--hints--

shiftArray([1, 2, 3], 1) should return [2, 3, 1].

js
assert.deepEqual(shiftArray([1, 2, 3], 1), [2, 3, 1]);

shiftArray([1, 2, 3], -1) should return [3, 1, 2].

js
assert.deepEqual(shiftArray([1, 2, 3], -1), [3, 1, 2]);

shiftArray(["alpha", "bravo", "charlie"], 5) should return ["charlie", "alpha", "bravo"].

js
assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], 5), ["charlie", "alpha", "bravo"]);

shiftArray(["alpha", "bravo", "charlie"], -11) should return ["bravo", "charlie", "alpha"].

js
assert.deepEqual(shiftArray(["alpha", "bravo", "charlie"], -11), ["bravo", "charlie", "alpha"]);

shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15) should return [5, 6, 7, 8, 9, 0, 1, 2, 3, 4].

js
assert.deepEqual(shiftArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 15), [5, 6, 7, 8, 9, 0, 1, 2, 3, 4]);

--seed--

--seed-contents--

js
function shiftArray(arr, n) {

  return arr;
}

--solutions--

js
function shiftArray(arr, n) {
  const len = arr.length;
  n = n % len;
  if (n < 0) n += len;

  return arr.slice(n).concat(arr.slice(0, n));
}