LoginSignup
1
0

More than 3 years have passed since last update.

【javascript】配列内の要素を指定INDEXの前(後)に移動

Last updated at Posted at 2020-09-18

紆余曲折を経てこの形に落ち着きそう。

(追記)delete演算子を使うのはよろしくなかったかな?

引数解説

変数 説明
1 arr Array 処理対象の配列
2 idx Number 移動する要素のINDEX
3 mIdx Number 移動先のINDEX
4 after Boolean true : mIdxの後方に挿入
false / 省略 : 前方に挿入

コード


const moveElement = (arr, idx, mIdx, after=false) => {
    //事前処理は省略
    arr = [...arr];
    if (after) mIdx++;

    const elm = arr[idx];
    delete arr[idx];

    arr.splice(mIdx, 0, elm);
    return Object.values(arr);
};

//連番生成
const array = [...Array(10).keys()];

moveElement(array, 2, 8, true);     // [0, 1, 3, 4, 5, 6, 7, 8, 2, 9]
moveElement(array, 8, 2);           // [0, 1, 8, 2, 3, 4, 5, 6, 7, 9]

やっている事(追記)

  1. 移動する要素を取得
  2. 取得した要素の位置をdeleteでempty状態にする
  3. 配列の長さは変わらないので指定INDEXの前後へspliceで挿入
  4. Object.values()でempty状態の要素はスルーして配列を再構成

falsyな要素が消えても構わない場合は、deleteする代わりに空文字を代入。
Object.values()ではなくfilter(Boolean)でreturnするのもありでしょう。

1
0
2

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
1
0