What's In My Array
Mastering Array Search with some, indexOf, and includes in JavaScript
Arrays are some of the most common data types you work with as a programmer. We filter them, we map over them, we edit them and more. As we spend so much time with them, JavaScript has created some great helper functions to make them easier to work with. Let's look at checking if an array contains a specific value. Say we have a list of IDs and want to check if a given ID is inside the array.
We could use indexOf
which returns the first index the given value can be found at or -1
if not present.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.indexOf(idToCheck) !== -1;
console.log(exists) // true
Great if we want to grab the index simultaneously, but in this case, I don't care about the index. We could use some
that checks if at least one element matches the given value.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.some(id => id === idToCheck);
console.log(exists); // true
Nice, but now I am passing a function. I think we can slim this down by using includes
which returns a boolean if the array contains the passed value.
const ids = [1, 2, 3, 4, 5];
const idToCheck = 3;
const exists = ids.includes(idToCheck);
console.log(exists); // true
We have covered a few array methods here, but I love includes
it turns some validation checks into one-liners. All these methods have full browser support, but you can find a breakdown in the links below.