JavaScript check whether iterator includes value

Viewed 1076

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)
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.

Related