- Search Within Arrays
- Tell It When To Start! (Index, and Indexing Negatives)
- You cannot search for multiple items at once with
The syntax for
.includes(value, i), where
value is what we're searching for, can be an integer or string, and
Let's say we have an array of our moral character, and we want to know if our array contains certain items. With
.includes, we can easily do this! Let's take a look.
const morals = ["honor", "courage", "justice", "yourself"];
.includes to see if
morals has our courage!
To do this on arrays, we simply call the array and place the syntax of
.includes after it, as such:
// is the computer's response. If you want to see it, don't forget the
const morals = ["honor", "courage", "justice", "yourself"]; morals.includes("courage"); // true morals.includes("yourself"); // true morals.includes("funny"); // false
You can also pass in integers instead of strings!
const numbers = [12, 22, 33, 44, 55]; console.log(numbers.includes(22)); // true console.log(numbers.includes(39)); // false
If you would like to play with these examples, check out this CodePen!
Now that we have the basics of
.includes, let's look that that second thing
.includes can take. Let's review syntax:
Earlier, we were substituting things into the
value portion, now we will be substituting something in for
i, or the index. For the
.includes method, this means where the computer will start looking for the number.
Check out this code:
const cities = ["Dallas", "Miami", "New York City", "Seattle"];
When we just pass in a string to search for, as we did in the section previous, the computer defaults to 0 -- start at the beginning.
Notice the changes in output:
const cities = ["Dallas", "Miami", "New York City", "Seattle"]; cities.includes("Dallas"); // true cities.includes("Dallas", 0); // true cities.includes("Dallas", 1); // false
Pretty simple, right? Good! Now let's do the final thing with
.includes... Negative indexes! Woo!
[1, 2, 3] the 1 is an index of -3.
Let's see it under the microscope:
const people = ["Mike", "Jebs", "Sarah", "Gary", "Phil", "Merilyn", "Macy", "Stacy", "Hacy", "Lacy"]; people.includes("Lacy", -2); // true. JS starts its search at Hacy people.includes("Merilyn", -4) // false. JS starts its search at Macy
Congratulations, you now understand this simple yet powerful little method! Go out into the world, and fix all its problems using
Found this blog helpful? Didn't like it? Let me know!
Thanks, and Happy Coding!