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?

指定の位置への要素の追加 : splice()

Posted at

今回からは、paizaの「クエリメニュー」の問題に挑戦していく!

しばらく難易度は下がるかもしれないけど、しっかり基礎を学びたい!


問題概要

  • 整数 N, K, Q と、 長さ N の配列 Aが与えられる

  • A_K の後ろに Q を挿入した後の長さ N+1 の配列について、先頭から改行区切りで出力


入力例

3 1 57
17
57
83

出力例:

17
57
57
83







✅ OKコード例:

const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];

rl.on('line', (input) => {
  lines.push(input);
});

rl.on('close', () => {
  const [N, K, Q] = lines[0].split(' ').map(Number);
  const arrA = lines.slice(1);

  arrA.splice(K, 0, Q);

  arrA.forEach(v => console.log(v));
});

🔍解説 splice()


✅ 【基本構文】

array.splice(start, deleteCount, item1, item2, );

  • start
    → 配列のどの位置から操作を始めるか(0-indexed)

  • deleteCount
    → 何個要素を削除するか(0なら削除しない)

  • item1, item2, …
    → start の位置に挿入する要素(複数OK)




✅ 【特徴】

  • 配列を直接変更(破壊的)する
    → 元の配列がそのまま変わる

  • 削除だけ・挿入だけ・置換もできる
    → 何通りにも使える万能メソッド-

  • 戻り値は削除された要素の配列
    → 削除した要素を受け取って使える




✅ 【利点】

  • slice などと違って「元の配列を丸ごと作り直す」必要がない

  • pushpop のような「先頭や末尾」だけじゃなく、途中の要素を自在に追加・削除・置換できる

  • 柔軟な一括操作 が1行で済む




✅ 【実践例】

▶️ 1. 途中に要素を挿入

const arr = [1, 2, 3, 4, 5];

// index 2 の位置に 99 を挿入
arr.splice(2, 0, 99);

console.log(arr); // [1, 2, 99, 3, 4, 5]

index 2 の位置に 99 を挿入 → index 2 以降が後ろにずれる

だから 3 の前に入る。


🔍 指定要素の後ろに入れたい → splice(index + 1, 0, item);



▶️ 2. 途中の要素を削除

const arr = [1, 2, 3, 4, 5];

// index 1 から 2 つ削除
const removed = arr.splice(1, 2);

console.log(arr); // [1, 4, 5]
console.log(removed); // [2, 3]



▶️ 3. 途中の要素を置き換え

const arr = [1, 2, 3, 4, 5];

// index 1 から 2 個削除し、10 と 11 を挿入
arr.splice(1, 2, 10, 11);

console.log(arr); // [1, 10, 11, 4, 5]



▶️ 4. 末尾に追加する

普通は push を使うけど、splice でもできる。

const arr = [1, 2, 3];
arr.splice(arr.length, 0, 99); // index = length で末尾
console.log(arr); // [1, 2, 3, 99]




【splice と slice の違い】

  • splice → 元の配列を直接変更(破壊的)
  • slice → 元の配列はそのまま、新しい部分配列を返す(非破壊的)






🗒️ まとめ

  • 基本構文: array.splice(start, deleteCount, …items)

  • 破壊的・ 元の配列を直接変更する

  • 用途: 挿入・削除・置換を柔軟に

  • 戻り値:削除した要素の配列

  • 利点:中間要素の操作が1行でできる




僕の失敗談(´;ω;`)と解決法🐈






💡おまけ toSpliced()

toSpliced() は Array インスタンスのメソッドで、 splice() メソッドに対応するコピーメソッド(非破壊)

指定された位置の要素を除去したり置き換えたりした新しい配列を返す。


使い方は同じ。

※ES2023(ECMAScript 2023)で正式追加

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