How to check if an item exists in an array
Are there better ways than array.findIndex?
Say you had an array of numbers and you wanted to check if a certain number exists in that array. You can use indexOf (if it’s an array of primitive types) or findIndex, and check if the result is -1 (false) or the index of item (true).
const numbers = [1, 2, 3, 4];const does1Exist = numbers.indexOf(1) !== -1; => true
const does6Exist = numbers.indexOf(6) !== -1; => falseconst fruits = [
{ name: "apple", quantity: 1 },
{ name: "banana", quantity: 2 },
];const doesAppleExist =
fruits.findIndex((fruit) => fruit.name === "apple") !== -1;doesAppleExist => true
Now, let's say we need to check if 100 fruits exist in that array. We would be running .findIndex 100 times (running 100 iterations on the same array). In such a case, we should use Sets.
Take note that by creating a set, you will be using more memory so this method would not be appropriate if you are only looking up the array a few times.
Using sets, we can only know if the item exists in the array or not. What if we needed the item that we look up? For that, we would need to use Maps or Objects, for which you can check out this article.