30
17

【JS】includes()で特定要素を複数指定したいとき

Last updated at Posted at 2021-05-25

ES6で追加された includes() メソッドは、とても便利ですが、指定できる特定の要素はひとつしか指定できません。でも複数指定したいときはないでしょうか?この記事では特定の要素を複数指定する方法を紹介します。結論からいうと、includes() に特定要素は複数指定できないでの独自関数を作ります。

includes() の使い方

まず includes() の使い方をおさらいしてみましょう。すでにわかっているよ!という人は読み飛ばしてください。

Array.prototype.includes()

includes() メソッドは、特定の要素が配列に含まれているかどうかを true または false で返します。

const numArray = [1, 2, 3];

console.log(numArray.includes(2)); // 出力:true

const animals = ['cat', 'elephant', 'hipo'];

console.log(animals.includes('cat')); // 出力:true

このように使います。また、配列だけでなく文字列に対しても使えます。

String.prototype.includes()

includes() メソッドは、1 つの文字列を別の文字列の中に見出すことができるかどうかを判断し、必要に応じて true か false を返します。

const text = 'I have no idea about JavaScript';

const word = 'idea';

console.log(text.includes(word)); // 出力:true

includes() で特定要素を複数指定する

includes() だけではだめなので、 some()every() を使って独自の関数を定義していきます。

複数の特定要素のうちひとつでも当てはまったら true を返す独自関数

const isIncludes = (arr, target) => arr.some(el => target.includes(el));

解説

some()は配列の少なくとも一つの要素が、指定された関数で実装されたテストに合格するかどうかをテストします。

Array.prototype.some()

独自関数 isIncludes に特定要素の配列(arr)と検索したい要素(target)を渡してあげると truefalse を返します。

複数の特定要素のうち全部当てはまったら true を返す独自関数

const isAllIncludes = (arr, target) => arr.every(el => target.includes(el));

解説

every() は、配列内のすべての要素が指定された関数で実装されたテストに合格するかどうかをテストします。

Array.prototype.every()

独自関数 isIncludesと同じく特定要素の配列(arr)と検索したい要素(target)を渡してあげると truefalse を返します。

独自関数 isIncludesisAllIncludesの使い方

こんな感じで使います。検索したい対象が配列の場合、 forEach()を使えば良いかと思います。

const text = 'Beef or chicken ? Sorry, I have no Kebap.';
const fruits = ['banana', 'apple', 'orange', 'lemon'];
const searchWord1 = ['an', 'ge'];
const searchWord2 = ['chicken', 'Kebap'];

// 複数の特定要素のうちひとつでも当てはまったら true を返す
const isIncludes = (arr, target) => arr.some(el => target.includes(el));
// 複数の特定要素のうち全部当てはまったら true を返す
const isAllIncludes = (arr, target) => arr.every(el => target.includes(el));

// 配列fruitsに対して実行
fruits.forEach(elm => {
  console.log(elm, isIncludes(searchWord1, elm));
/* 出力:
"banana" true
"apple" false
"orange" true
"lemon" false
*/
});

// 文字列textに対して実行
console.log(isAllIncludes(searchWord2, text)); // 出力:true

感想

includes()で複数指定〜」といっておきながら、 includes() だけでは実現できませんでした。無念!

無理にincludes() を使わなくても indexOf や正規表現を使っても実現できるかと思いました。


参考

2024/06/19/追記
参考に上げていたサイトが怪しいサイトに置き換わっていたので削除しました。

30
17
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
30
17