arrays - JavaScript check whether iterator includes value - Stack Overflow

For a JavaScript array, the includes(value) function returns true, if and only if the array contains th

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)

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)
Share Improve this question asked Sep 27, 2020 at 21:17 YannicYannic 82810 silver badges27 bronze badges 5
  • 1 map.has() Map.prototype.has() – pilchard Commented Sep 27, 2020 at 21:26
  • 2 @pilchard, this checks only the key of a map. – Nina Scholz Commented Sep 27, 2020 at 21:27
  • That second one looks good. Sure, you need to stow away the helper function somewhere, but the call is short and efficient. Alternatively, use the proposed iterator helpers and check it.some(v => v === value). – Bergi Commented Sep 27, 2020 at 21:28
  • @Bergi can you make an answer? – qwr Commented Jun 15, 2021 at 22:40
  • @qwr done, see below – Bergi Commented Jun 16, 2021 at 9:28
Add a ment  | 

1 Answer 1

Reset to default 5

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 parison, which has a different result than === for a value of NaN.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745466686a4628945.html

相关推荐

  • arrays - JavaScript check whether iterator includes value - Stack Overflow

    For a JavaScript array, the includes(value) function returns true, if and only if the array contains th

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信