6.3 Finding Elements (Primitives)
Okay, now let's look at finding elements in an array. Finding elements really depends on whether you store primitive or reference types in an array. So I'm going to start with primitives because they're easier. And then I'll show you how to find reference types in an array. So, let's say we have an array of numbers, with 4 elements. 1, 2, 3, 4. Here we have a method called indexOf, we pass in the element we're looking for, and if that element exists in the array, this method will return the index of that element in the array. If it doesn't exist, it will return minus 1. Let me show you a few different examples. So first I'm going to pass the character a, obviously we don't have that element so the result we'll see will be minus 1. So index of returns the index of the given element in this array. However, if I change that to 1, we get 0, because the index of that element is 0, note that the type of that element is important, so if I pass 1, as a string here, we again get minus 1, because we don't have 1 as a string in this array, we have it as a number. Now similar to the indexOf, we have another method called lastindexOf. And this will return the last index of the given element or minus 1 if it doesn't exist. So, to demonstrate this, I'm going to add another 1 here, now let's do another console. log, numbers. lastIndexof 1. Save the changes. So, lastindexOf 1 is 3, because it's here, and the index of this element is 3. So, basically, to see if a given element exists in an array, we can do something like this. Console. Log numbers.indexOf 1 which is not less than 1. If this expression returns true, it means that this element exists in the array. Let's take a look, save the changes, we get true here. But this is a bit ugly, we have a new method in JavaScript to do the same thing. So we do a console. Log of numbers.includes of 1. This simply returns true if the given element exists in the array. Let's take a look, then save the changes and we get true here. Now, all methods have a second parameter that is optional. And this is the starting index. For example, with the indexOf let's change that to 1 as a number, so save the changes, you can see that the indexOf 1 is 0. Because it's here. However, I can pass a second argument here, this second argument is from the index. And this is the index from which the search will start. So I can pass 2 here, that is 0, 1, 2, our search will start here, let's see what we get. Save the changes, so we get 3 which is the index of the second in this table. That's it for this video, let's meet again then for the next video where we will see the search for elements in an array with reference types.