Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列を「回転」させる

Last updated at Posted at 2024-10-18

[ 0, 1, 2, 3, 4 ][ 3, 4, 0, 1, 2 ] みたいなことをやりたいが、すぐ忘れるのでメモ。

    let array = [ 0, 1, 2, 3, 4 ];
    array = array.splice(3).concat(array);

これで array が [ 3, 4, 0, 1, 2 ] に変更される。再代入を忘れずに。

array.splice(3) は array から添字 3 以降の要素を取り除いて返す。つまり、[ 3, 4 ].concat([ 0, 1, 2])[ 3, 4, 0, 1, 2 ] となる寸法。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Comments

diywmk9
@diywmk9

splice()だけで行なえば再代入不要です。

  const array = [0, 1, 2, 3, 4];
  array.splice(0, 0, ...array.splice(-2));
  console.log(array); // [3, 4, 0, 1, 2]

また、push()pop()shift()unshift()を組み合わせれば、1要素ずつ左右にローテートする処理も作れます。

  const rotateLeft  = arr => arr.push(arr.shift());
  const rotateRight = arr => arr.unshift(arr.pop());

  const array = [0, 1, 2, 3, 4];

  for (let i = array.length; i--;) {
    rotateLeft(array);
    console.log(array);
  }
  // [1, 2, 3, 4, 0]
  // [2, 3, 4, 0, 1]
  // [3, 4, 0, 1, 2]
  // [4, 0, 1, 2, 3]
  // [0, 1, 2, 3, 4]

  for (let i = array.length; i--;) {
    rotateRight(array);
    console.log(array);
  }
  // [4, 0, 1, 2, 3]
  // [3, 4, 0, 1, 2]
  // [2, 3, 4, 0, 1]
  // [1, 2, 3, 4, 0]
  // [0, 1, 2, 3, 4]
0

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz)

View event details

Being held Article posting campaign

1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address