Array.splice()

spliceの英単語としての意味は、

動詞

  1. (縄、フィルムなどを)継ぎ合わせる
  2. 2つのものを継ぐ
  3. (DNAなどを)接合する
  4. 結婚する

名詞

  1. 組み継ぎ、より継ぎ

使い方

配列に対する削除、追加、置換などに使う。

リアクティブにデータを変更しなければならないVue.jsでは特に頻繁に使う。

配列操作はもはやspliceだけでいい。

const arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

サンプルコード

const months = ['Jan', 'March', 'April', 'June'];
// index1から0個の要素を削除し、'Feb'を挿入
months.splice(1, 0, 'Feb');
console.log(months);
// ["Jan", "Feb", "March", "April", "June"]

// index4から1個の要素を削除し、'May'を挿入
months.splice(4, 1, 'May');
console.log(months);
// ["Jan", "Feb", "March", "April", "May"]

// 複数挿入
months.splice(0, 0, 'a', 'b');
console.log(months);
// ["a", "b", "Jan", "Feb", "March", "April", "May"]

応用編

前の要素と入れ替え

以下の配列の要素、'b’をその前の’a’と入れ替えたい。

const array = ['a', 'b', 'c', 'd'];

// 入れ替える'b'のindex
const index = array.indexOf('b')

array.splice(index - 1, 2, array[index], array[index - 1]);
console.log(array)
// ['b', 'a', 'c', 'd']

後ろの要素と入れ替え

以下の配列の要素、'b’をその後ろの’c’と入れ替えたい

const array = ['a', 'b', 'c', 'd'];

// 入れ替える'b'のindex
const index = array.indexOf('b')

array.splice(index, 2, array[index + 1], array[index]);
console.log(array)
// ['a', 'c', 'b', 'd']

参考

https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/splice