JavaScriptに関するお知らせ

SINCE2019
>
【JS】配列検索はsome?every?find?indexOf?includes?test?exec?match?search?

【JS】配列検索はsome?every?find?indexOf?includes?test?exec?match?search?


こんにちは!今日は配列検索、つまり「配列に含むか」を探す系のメソッドを比較します。

最も簡単な方法

数列の中から特定の数字を探すようなケースを想定すると...

const arr = [0, 1, 2, 0, 8, 2, 8, 8, 2, 8]

includes

一番シンプルなのは.includesですね:)

const answerTrue = arr.includes(8)
const answerFalse = arr.includes(7)

console.log(answerTrue) // true
console.log(answerFalse) // false

8は含まれているのでtrue、7はないのでfalse。

かなり簡単な方法

indexOf

.includesはレガシーブラウザだと未対応だったりします。

そんな場合は.indexOf使いましょう:)

const answerTrue = !!~arr.indexOf(8)
const answerFalse = !!~arr.indexOf(7)

console.log(answerTrue) // true
console.log(answerFalse) // false

ちょっと黒魔術チックですがまあ簡単です。

若干面倒な方法

some

ぶっちゃけ上2つで十分ですが.someもやってみます。

以後console.log省略。

const answerTrue = arr.some(n => n === 8) // true
const answerFalse = arr.some(n => n === 7) // false

find

.findだとこう。

const answerTrue = !!arr.find(n => n === 8) // true
const answerFalse = !!arr.find(n => n === 7) // false

.findのこのやり方はfalsyな値(0とか)の操作には使えないです

every

今回の例のように数字のみならこんなのも可。ちょっと短くなります。ちょっとすぎだろ。

const answerTrue = arr.every(n => n - 8) // true
const answerFalse = arr.every(n => n - 7) // false

超面倒(正規表現)

取り入れられた正規表現、加速した糞コードは危険な領域へと突入する。

test

const answerTrue = RegExp(`^(${arr.join('|')})$`).test(8) // true
const answerFalse = RegExp(`^(${arr.join('|')})$`).test(7) // false

exec

const answerTrue = !!RegExp(`^(${arr.join('|')})$`).exec(8) // true
const answerFalse = !!RegExp(`^(${arr.join('|')})$`).exec(7) // false

match

const answerTrue = !!`${8}`.match(RegExp(`^(${arr.join('|')})$`)) // true
const answerFalse = !!`${7}`.match(RegExp(`^(${arr.join('|')})$`)) // false
const answerTrue = !!~`${8}`.search(RegExp(`^(${arr.join('|')})$`)) // true
const answerFalse = !!~`${7}`.search(RegExp(`^(${arr.join('|')})$`)) // false

おわりに

.includesが優秀すぎて比較する余地がなかったわ。



PREV
2019-05-02
【JS】reduceで複雑な配列操作-最も古い4文字の元号の次の元号は?

NEXT
2019-05-05
【JS】Pontaの実質還元率をJavaScriptで求める