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;
}
Index is not -1
function compareHas(arr, x) {
return arr.indexOf(x) !== -1;
}
Using includes
function includesHas(arr, x) {
return arr.includes(x);
}
Some
function someHas(arr, x) {
return arr.some(item => item === x);
}
Bitwise not
indexOf
If you want to don't understand your code.
function bitwiseHas(arr, x) {
return !!~arr.indexOf(x);
}
~-1 === 0
, then !!0 === false
, any other number than 0
is truthy.
With Set
function setHas(arr, x) {
return new Set(arr).has(x);
}
* Filter π΅
function filterHas(arr, x) {
return !!arr.filter(item => x === item).length; // π
}
* Reduce π±βπ€
function reduceHas(arr, x) {
return arr.reduce(function (has, item) {
if (!has) return item === x;
return has;
}, false); // π£
}
What piece of code are you using for that task? What is the strangest, but efficient way to do that?
Top comments (2)
An interesting add to this article would be benchmarks to see which is the most efficient method?
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.