0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【JavaScript関数ドリル】を毎日やる【勉強用】

Posted at

#【JavaScript関数ドリル】初級編のwithout関数の実装のアウトプット

##without関数の課題内容

##without関数に取り組む前の状態

  • 第2引数以降の引数をまとめて受け取る方法が全くわからない
  • 元の配列から引きたい数値をループして引いていけば良さそうだ

##without関数に取り組んだ後の状態

  • 解説動画を見ずに実装できた
  • 最初はfor文を使って値を新たな配列にpushしようとしたが、ifを使う前にreturnしていたのが原因でうまく代入できなかった
  • 検索の過程で「Set」「indexOf」「lastIndexOf」について知ることができた

##without関数の実装コード(答えを見る前)

const without = (array, ...removeArray) => {
    const concatArray = array.concat(removeArray);
    return concatArray.filter((value, index, self, ) => self.indexOf(value) === self.lastIndexOf(value));
};

console.log(without([2, 1, 2, 3], 1, 2));
//[3]

検索したワード
「javascript 引数 まとめて受け取る」
「javascript 配列 重複を削除」
「javascript 配列 結合」等々

##without関数の解答コード

function without(array, ...values) {
  const newArray = [];
  for(let i = 0; i < array.length; i++) {
    const candidateToPush = array[i];
    // values : [1, 2]
    // array: [2, 1, 2, 3]
    // candidateToPush: 2, 1, 2, 3
    if( !values.includes(candidateToPush) ) {
      newArray.push(candidateToPush);
    }
  }

  return newArray;
}

console.log( without([2, 1, 2, 3], 1, 2) );
// => [3]
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?