3
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?

More than 5 years have passed since last update.

Array.prototype.filter() とか、配列操作時の3つの引数が理解できない

3
Last updated at Posted at 2018-10-26

実際に記事として書いていきながら検証していけば、理解も深まると思ったのでやって見ます。


僕の思い
いつまでもforだけでやりたくない。
filtermapって書いてあるだけで、意図もわかりやすいので使いこなしたい。
元々の配列は壊さず、新しく配列を作って返してくれるのが嬉しい!
3つの引数?え?


引数が3使えるって意味不明

それぞれがどのような役割なのかがわからないので、順番に検証して確かめていきます。

1つ目の引数は何をしているの?

const filtered = [1, 2, 3, 4, 5].filter((element, index, array) => {
    console.log(element) //1つ目の引数
    return element >= 4;
    });
console.log(filtered)//結果

結果

1
2
3
4
5

[4, 5]

なるほど、元の配列の要素が1個づつ順番に吐き出されるわけですね。
結果として、4未満のものは全て削除された新しい配列が返りました

2つ目の引数は何をしているの?

const filtered = [1, 2, 3, 4, 5].filter((element, index, array) => {
    console.log(index)//2つ目の引数
    return 3 === index;
    });
console.log(filtered)//結果

結果


0
1
2
3
4

[4]

なるほど、filterにかけた配列の要素は5つあるから、0~4までを順番に1つづつ当てはめてるわけですね。
結果として [4]となっているのは、元の配列の中の、0から数えて3番目の数字が返ったからですね。

3つ目の引数は何をしているの?

const filtered = [1, 2, 3, 4, 5].filter((element, index, array) => {
    console.log(array)//3つ目の引数
    return 3 === index;
    });
console.log(filtered)//結果

結果

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

[4]

なるほど、元の配列が入っているんですね。
元の配列の要素は5つあるから、5回元の配列が吐き出されたのか。

配列を操るために必要な引数の使い方を知る事ができました。


React TODOリストの削除ボタンサンプル
作業を終えてデリートボタン押した時に
ボタンを押した要素のindex番号以外の要素を残して吐き出す事ができる。

    onPressDelete(arg) { //押された番号を持った関数
        this.setState({
            //条件にあうものだけを抽出して再描画。
            todos: this.state.todos.filter((t, i) =>i !== arg),
        })
    }

間違っていたり、参考になるサイトやソース、リポジトリ等あれば教えてくださいませ!!

3
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
3
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?