In most languages, indexOf() returns -1 if element is not found, which IMO is a bit counter productive. What's the best alternative to this in you programming language? Is there any function that will just return a boolean value indicating if the element was found?
I'd suggest you use binary search for searching for the element; if a valid array index is there, return true, else return false.
Now, adapting it for different scenarios is another story. However, if you want an example, I would love to expand this! :)
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
const index = fruits.findIndex(fruit => fruit === "blueberries");
console.log(index); // 3 console.log(fruits[index]); // blueberries
exemple from MDN
Why is -1 "counterproductive"?!? Is it so hard to type "!== -1" or ">= 0"?
Peter Scheler
JS enthusiast
In JavaScript you can use
.includes()to return a boolean.If you not searching by an element but by condition you can also use
.some()to return true or false and.find()to return the value/object orundefined.Tip: If you don't like
[1, 2, 3].indexOf(4) !== -1you can write~[1, 2, 3].indexOf(4). (Type is still Number!)