DEV Community

Cover image for Is item in array?
Hub
Hub

Posted on • Updated on

Is item in array?

Task: Check if item is in array. Return boolean.

for loop

function forHas(arr, x) {
  for (let item of arr) {
    if (item === x) {
      return true;
    }
  }
  return false;
}
Enter fullscreen mode Exit fullscreen mode

Index is not -1

function compareHas(arr, x) {
  return arr.indexOf(x) !== -1;
}
Enter fullscreen mode Exit fullscreen mode

Using includes

function includesHas(arr, x) {
  return arr.includes(x);
}
Enter fullscreen mode Exit fullscreen mode

Some

function someHas(arr, x) {
  return arr.some(item => item === x);
}
Enter fullscreen mode Exit fullscreen mode

Bitwise not indexOf

If you want to don't understand your code.

function bitwiseHas(arr, x) {
  return !!~arr.indexOf(x);
}
Enter fullscreen mode Exit fullscreen mode

~-1 === 0, then !!0 === false, any other number than 0 is truthy.

With Set

function setHas(arr, x) {
  return new Set(arr).has(x);
}
Enter fullscreen mode Exit fullscreen mode

* Filter 😵

function filterHas(arr, x) {
  return !!arr.filter(item => x === item).length; // 😂
}
Enter fullscreen mode Exit fullscreen mode

* Reduce 🐱‍👤

function reduceHas(arr, x) {
  return arr.reduce(function (has, item) {
    if (!has) return item === x;
    return has;
  }, false); // 💣
}
Enter fullscreen mode Exit fullscreen mode

What piece of code are you using for that task? What is the strangest, but efficient way to do that?

Top comments (2)

Collapse
 
martin2844 profile image
martin2844

An interesting add to this article would be benchmarks to see which is the most efficient method?

Collapse
 
tnifey profile image
Hub

I made a quick benchmark with that code.
jsbench.me/5xkmowvikx/1

It seems that includes is the fastest on Chrome, on Firefox indexOf and bitwise is the winner. On Firefox on Android seems like its includes and bitwise are winners.

The slowest method is using Set.