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

【Typescript】配列の中から条件に一致する要素を探す

Last updated at Posted at 2020-08-28

使うことが多いので、まとめる

特定の値(一種類)に一致するものがあるかを知りたい

array1 = [1, 2, 3];
const result = this.array1.includes(1);
//または
const result2 = this.array1.some((val) => val === 1);

一致する物があればtrue,なければfalse
配列の要素が複雑な形してなければincludesがシンプル。

特定の値(複数種類)に一致するものがあるかを知りたい

array1 = [1, 2, 3];
array2 = [3, 4, 5];
const result =
 this.array1.some((val) => this.array2.includes(val));

配列1から配列2のいずれかの値があるかを調べたいとき
一致する物があればtrue,なければfalse

8/31 追記
const result = this.array1.includes( 3 || 4 || 5 );
調べたい要素数が少なければincludesで||が楽そう

コメントご指摘。
調べてるときこういう書き方があってこの例だとtrueになるからこういう書き方できるのか〜と思ってましたが
||ではできないみたいです。教えていただきありがとうございます:hugging:

配列の中から特定の値に一致する物があれば、その要素を取得したい

array3 = [
    { a: 1, b: 2 },
    { a: 3, b: 4 },
    { a: 5, b: 6 },
  ];
const result3 = this.array3.find((val) => val.a === 1);

一致する物があれば、その要素の値を返り値にする(この例だと、{a:1,b:3})

booleanで知りたければincludesかsome、
値そのものが欲しければfind!

1
0
2

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