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?

先頭の要素の削除 shift()

Posted at

今回は paizaの「先頭の要素の削除」の問題に挑戦!

配列の要素を削除する必要がある場面に遭遇したことがなかったから、そのメソッドの存在自体は知ってても使ったことがなかったので、初挑戦!


問題概要

数列 A と入力の回数 K が与えられるので、K 回の入力に応じて次のように処理せよ。

  • pop
    A の先頭の要素を削除する。既に A に要素が存在しない場合何もしない。

  • show
    A の要素を先頭から順に改行区切りで出力する。A に要素が存在しない場合何も出力しない。


入力例:

5 3
7564
4860
2410
9178
7252
pop
pop
show

出力例:

2410
9178
7252






✅ OKコード例

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

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


rl.on('close', () => {
    const N = Number(lines[0]);
    const arrA = lines.slice(1).map(Number);
    
    arrA.shift();
    
    console.log(arrA.join('\n'));
});




✅ shift() とは

  • 何する?
    配列の先頭要素を1つだけ削除して返す

  • 元の配列は?
    破壊的 →元の配列から先頭の要素が消える

  • 戻り値
    削除した要素。 配列が空なら undefined

  • 引数
    取らない!必ず () は空



📌 基本構文

const first = arr.shift();



📌 使用例

const arr = [10, 20, 30];
const removed = arr.shift();

console.log(removed); // 10
console.log(arr);     // [20, 30]



✅ shift() は必ず「1個だけ」

  • shift(1) のように数字を渡しても無視される。

  • 先頭要素以外は自動では削除しないので、複数削除したいときは他のメソッドを使う!



✅ 複数削除・非破壊なら?

📌 1️⃣ splice()

  • 範囲指定で削除できる(破壊的)

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

// index 0 から 3 個削除
arr.splice(0, 3);

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

📌 2️⃣ slice()

  • 範囲指定で部分配列を作れる(非破壊的)

  • 元の配列は変わらない。


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

const newArr = arr.slice(3); // index 3 以降

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






🗒️ まとめ

shift() は 配列の先頭要素を1つだけ削除して、その要素を返すメソッド!




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

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?