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 3 years have passed since last update.

【JavaScript】find()とfilter()の使い分けまとめ

Last updated at Posted at 2020-06-06

#はじめに

配列の中から特定の要素を取り出す時、
ひとつ→find()
複数→filter()
を使うけど、返す値が異なることを覚えておきたい。

#ソースコード
配列の中から10以上の値を取り出す。
###findメソッド

const array = [5, 120, 10, 10, 4];

const result = array.find(element => element >= 10);

console.log(result);
//120

120という値だけが返される。

###filterメソッド

const array = [5, 120, 10, 10, 4];

const result = array.filter(element => element >= 10);

console.log(result);
//[120, 10, 10]

10以上の値だけが入った新しい配列が返される。
filterメソッドを使ってこの配列から120を取り出したい場合は、

result[0]

で値を取り出す。

#まとめ

find()は配列の要素の値を返して
filter()は関数内で条件が一致する値だけを格納した新しい配列を返す。

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?