Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check whether iterator includes value

For a JavaScript array, the includes(value) function returns true, if and only if the array contains the value. What is a good and performant equivalent to check, whether a value is included in an iterator (e.g. map.values())?

First approach (maybe not the most performant one):

Array.from(it).includes(value)

Second approach (not that short):

const iteratorIncludes = (it, value) => {
  for (x of it) {
    if (x === value) return true
  }
  return false
}
iteratorIncludes(it, value)
like image 992
Yannic Avatar asked Aug 07 '26 13:08

Yannic


1 Answers

Your second approach looks good. Sure, you need to stow away the helper function somewhere, but you need to declare it only once so it doesn't matter - the call is short and efficient (even shorter than your first approach).

Alternatively, use the proposed iterator helpers and check it.some(v => v === value)1. They don't offer an includes method that mirrors the Array API yet.

1: Technically, includes uses the SameValueZero comparison, which has a different result than === for a value of NaN.

like image 98
Bergi Avatar answered Aug 10 '26 01:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!