JS 学び直しメモ:slice と splice をどう使い分けるか

最近、JavaScript の基礎理解があいまいだと感じたため、あらためて 1 から学び直しています。毎日少しずつ学習し、理解した内容を記録として残していくことにしました。

今回は Udemy の学習を通して、slice と splice の使い分けに少しずつ慣れてきたので、その内容をまとめます。

なお学習した講座はこちらです。

  • The Complete JavaScript Course 2025: From Zero to Expert!
  • チャプター 155「CHALLENGE #1」
    そこで課題があり、指示の要約は以下です。

英語話者の講座ですが、日本語字幕もでも学習できます。ただ読みにくい文章もあるため、英語の字幕を表示させて学習しました。

Create a function called checkDogs(dogsJulia, dogsKate) that:
Makes a shallow copy of Julia’s data and removes the first and last two elements (they are cats, not dogs)
・Combines Julia’s corrected data with Kate’s data into one array
・Logs for each dog whether it is an adult or a puppy
・Adult: Dog number 1 is an adult, and is 5 years old
・Puppy: Dog number 2 is still a puppy 🐶
・Runs the function for both test datasets

checkDogs(dogsJulia, dogsKate) という関数を作成する。
Julia の配列を シャローコピーし、先頭 1 つ+末尾 2 つを削除(猫のデータのため)。修正後の Julia データと Kate のデータを 1 つの配列に結合
– 各犬について、成犬か子犬かをコンソールに表示
– 成犬:Dog number 1 is an adult, and is 5 years old
– 子犬:Dog number 2 is still a puppy 🐶
– 両方のテストデータで関数を実行する

完成コードはこちら

完成コードはこちらです。

const checkDogs = function (dogsJulia, dogsKate) {
  const dogsJuliaCorrected = dogsJulia.slice();
  dogsJuliaCorrected.splice(0, 1);
  dogsJuliaCorrected.splice(-2);
  // console.log(dogsJuliaCorrected);
  const dogs = dogsJuliaCorrected.concat(dogsKate);
  console.log(dogs);
  // 5,2,4, 1, 15, 8, 3

  dogs.forEach(function (dog, i) {
    if (dog >= 3) {
      console.log(`Dog number ${i + 1} is an adult, and is ${dog} years old`);
    } else {
      console.log(`Dog number ${i + 1} is still a puppy🐶`);
    }
  });
};

checkDogs([3, 5, 2, 12, 7], [4, 1, 15, 8, 3]);

気をつけた点は、元の配列を直接変更しないよう、まず slice() でコピーを作成し、その後 splice() で必要な要素だけを削除したところです。

forEach は何度か書いているので、条件分岐の記述もスムーズに書けるようになってきました。

また配列の結合には concat を使用しました。push で追加する方法もありますが、元の配列を変更しない方針に合わせて、新しい配列を返す concat を選びました。