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?

【JavaScript】配列の応用まとめ③(条件式に合う最初の要素を返却)

Last updated at Posted at 2025-01-26

JS基礎学習、今回は配列の応用編③!

▼配列の応用

1. 条件式に合う最初の要素を返却する方法

  • find メソッド
// 例
const numbers = [1,2,3,4,5,10,20,30]

// 偶数があれば最初の要素を返却
const findEven = numbers.find(num => num % 2 === 0);

// アロー関数を使わない場合
const findEven = numbers.find(function(num) {
  return num % 2 === 0;
});

console.log(findEven); // 2が返却される

findメソッドはオブジェクトも取得可能です。

<応用例>

  • ユーザー管理システム
    • ユーザーIDや名前、メールアドレスなどで検索する
  • 在庫管理システム
    • 商品IDや名前で検索して在庫状況を確認する
  • コンテンツ管理システム(CMS)
    • 投稿IDやタイトルで記事を検索する
const users = [
  { id: 1, name: "Alice", email: "alice@examplexxxx.com" },
  { id: 2, name: "Bob", email: "bob@examplexxxx.com" },
  { id: 3, name: "Charlie", email: "charlie@examplexxxx.com" },
];

const userByEmail = users.find(user => user.email === "bob@examplexxxx.com");
console.log(userByEmail);

//「user.email === "bob@examplexxxx.com"」の条件と一致しているオブジェクトを持ってきてくれる

// 結果: { id: 2, name: "Bob", email: "bob@examplexxxx.com" }

▼参考

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?