0
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 1 year has passed since last update.

【備忘録】Next.jsで配列からデータを取り出すときに使う関数

0
Posted at

ドキュメントや解説サイトを見れば一発なのですが、いつも忘れるのでメモ書きします。代表的な3つです。

Find()

条件に合致した最初の1つだけ取ってくる関数です。
合致したものがない場合はundefindが返ってくるので、それを踏まえた型指定が必要です。

使用例

const kudamono = ["りんご","梨","洋ナシ"];
const kudamonoItem = kudamono.find((item)=> item === "梨");
console.log(kudamonoItem);
----------------出力---------------------
梨

Filter()

条件に合致したものを配列として返します。
一致したものを、さらに他のものと照合するときに便利です。
indexも使えます。
説明だけを聞いてもパッとしませんが、例を見るとはっきり分かると思います。

使用例

const yasai = ["小松菜","白菜","レンコン","水菜","かぶら"];
//yasaiの中から3文字のものを取り出す
const len2Yasai = yasai.filter((item)=> item.length === 3);
//["小松菜","かぶら"]が取り出される
//さらにindexが2で割り切れるものを取り出す
const len2YasaiIndex = len2Yasai.filter((item,index)=> index % 2 === 0);
console.log(len2YasaiIndex);
----------------出力---------------------
かぶら

some()

条件に合致したものがそもそも存在するかを判定するものです。特に中身を取り出す必要のない際に使用すると便利です。

使用例

const nippai = ["牛乳","豆腐"];
//nippaiの中に2文字のものがあるか判定
const isNippai = nippai.some((item)=> item.length === 2);
console.log(isNippai);
----------------出力---------------------
true
0
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
0
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?