LoginSignup
19
19

More than 5 years have passed since last update.

配列の要素を指定位置に移動させる

Last updated at Posted at 2017-04-13

配列内の要素を指定位置へ移動させる
D&Dで要素を並び替えした時にデータを保存してあるcollectionに対してよく使うのでメモ

function moveAt(array, index, at) {
    if (index === at || index > array.length -1 || at > array.length - 1) {
      return array;
    }

    const value = array[index];
    const tail = array.slice(index + 1);

    array.splice(index);

    Array.prototype.push.apply(array, tail);

    array.splice(at, 0, value);

    return array;
  }

実行結果

  function fruitsMove(index, at) {
     const fruits = ['apple', 'banana', 'grape', 'orange', 'peach'];

     moveAt(fruits, index, at);

     console.log(fruits);
  }

  // 'apple' を fruits[1] へ移動
  fruitsMove(0, 1) // => ["banana", "apple", "grape", "orange", "peach"];

  // 'peach' を fruits[1] へ移動
  fruitsMove(4, 1); // => ["apple", "peach", "banana", "grape", "orange"]

  // 'apple' を fruits[4] へ移動
  fruitsMove(0, 4); // => ["banana", "grape", "orange", "peach", "apple"]

  // 'peach' を fruits[0] へ移動
  fruitsMove(4, 0); // => ["peach", "apple", "banana", "grape", "orange"]
19
19
0

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