0

Sorry if this is a pretty basic question, but I never had this problem before. I'll show what I mean in a pretty basic way:

Let's say I have the array [1, 2, 3]. How can I turn it into [3, 1, 2] or [2, 3, 1] (move each element 1 to the right or the left)? Thanks in advance!

pierreh
  • 149
  • 7

2 Answers2

1

Try this:

var x = [1, 2, 3];

console.log(x);

// shift right
x.unshift(x.pop());

console.log(x);

// shift left

x.push(x.shift());

console.log(x);

Check here to see what these methods do.

Keith
  • 15,057
  • 1
  • 18
  • 31
Shell Code
  • 579
  • 2
  • 7
0

function shiftRight(arr) {
  if (arr.length < 2) return arr;
  return [arr[arr.length-1], ...arr.splice(0, arr.length - 1)];
}
function shiftLeft(arr) {
  if (arr.length < 2) return arr;
  return [...arr.splice(1, arr.length - 1), arr[0]];
}
console.log(shiftLeft([1, 2, 3, 4, 5]));
console.log(shiftRight([1, 2, 3, 4, 5]));
Prime
  • 2,544
  • 1
  • 3
  • 19