FreeCodeCamp and JavaScript: the indexOf Method()

Today’s post is on the indexOf() method, which will tell you the first position in an array that an element appears, or returns a -1 (negative one) if it isn’t in the array.  This is handy when you want to know whether a number, character, string, or whatever is in an array or not.  It’s also useful when searching for duplicates.

From MDN, the syntax:

arr.indexOf(searchElement[, fromIndex = 0])

We have two parameters in the above method:

searchElement – This is whatever element you want to find.

fromIndex – this is the spot to start at in the array.  It’s optional.  If you give a number that’s equal to or greater than the length of the array (array.length), of course, you’re going to get a -1 back.  As with several of the methods I’ve discussed on the blog, you can put a negative number for this parameter and it will start from that index but go from front to back in the array.  The default, if you don’t put anything, is index 0.

Finally, note that indexOf() uses strict equality, or ===, too.  Keep that in mind!

MDN then gives a number of simple examples:

var array = [2, 9, 9];

array.indexOf(2); // 0

2 has an index of 0, because it’s the first element in the array.  Remember, arrays start with element[0] in JavaScript!

array.indexOf(7); // -1

There is no -7 in the array, so the indexOf() method returns -1.

array.indexOf(9, 2); // 2

We are looking for the index of 9, starting at element[2].  Element[2] just happens to be 9, so we get 2 back.

array.indexOf(2, -1); // -1

We are looking for 2, beginning at element 1 – 1 back from the length of the array, which is 2.  Element 1 is -1, and then we move FORWARD, to the next element.  There ISN’T a next element, so the search terminates and you get -1 back.

array.indexOf(2, -3); // 0

We are looking for 2, beginning at element -1.  That doesn’t exist, of course, so the search will begin at element[0], which happens to be 2.  So we get a 0 back.

Next, MDN asks what happens if we want to know ALL of the occurrences of an element in an array, not just the first?  Here’s the code:

var indices = [];
var array = [‘a’, ‘b’, ‘a’, ‘c’, ‘a’, ‘d’];
var element = ‘a’;
var idx = array.indexOf(element);
while (idx != -1) {
  idx = array.indexOf(element, idx + 1);

// [0, 2, 4]

First, we create a blank array called ‘indices’.  This is going to contain the locations of all the elements that match the one we’re looking for.  Next we create an array and then we decide we’re going to look for the character ‘a’.

We assign the index of a to the variable idx.  This line also searches the array to make sure the element we are looking for is in the array to begin with.

Now we enter a while loop.  The loop will begin by checking to see if idx is -1.  If this is the first time through, and the line before it has already set the value of idx to -1 because the element we want isn’t even in the array, we’ll skip the loop and return -1.

Then the while statement ‘pushes’ the value of idx into indices.  If this is the first time through, the first value to be pushed into indices is the first location of the element we are looking for.  If not, this will be the next location found by the lines below.

the next line is idx = array.indexOf(element, idx + 1);  This is the heart of the loop.  We perform the same search as before, looking for the next occurrence of the element, but starting at the element AFTER the occurrence we already found.  That way we don’t keep getting the same occurrence back.  We work to the end of the array.  Eventually we’ll hit a point where there are no more occurrences of our element to be found, or we’ll hit the end of the array, and we’ll get -1 back.  This will terminate the loop.

The next line prints the indices array with all the indices (thuis the name of the array) where our element is to be found.  In this case, the letter a can be found at elements{0], [2], and [4].

Finally, MDN gives an example where we want to search an array, see if an element is in it, and if not, modify it.

function updateVegetablesCollection (veggies, veggie) {
  if (veggies.indexOf(veggie) === -1) {
             console.log(‘New veggies collection is : ‘ + veggies);
         } else if (veggies.indexOf(veggie) > -1) {
             console.log(veggie + ‘ already exists in the veggies collection.’);

We have a function called updateVegetablesCollection that receives two parameters, an array called veggies and a veggie to add.  First, we check the whole array to see if the element is in it already.  This is the if statement saying that if we look and get -1 back then proceed, else print that it already contains that element in the console.

Assuming it’s a new element, then, we’re going to add it to the array and output the modified array to the console.

Let’s see this in action.

     var veggies = [‘potato’, ‘tomato’, ‘chillies’, ‘green-pepper’];

So, we’re going to work with an array called veggies that contains the elements ‘potato’, ‘tomato’, ‘chillies’, and ‘green-pepper’.

updateVegetablesCollection(veggies, ‘spinach’);
          // New veggies collection is : potato, tomato, chillies, green-pepper, spinach

We’re going to add spinach to the veggies array.  After we do so, the array now contains it right there at the end.

updateVegetablesCollection(veggies, ‘spinach’);
// spinach already exists in the veggies collection.

We’re going to add spinach to the veggies array…again.  But this time the indexOf() method returns -1, because we already added spinach.

And that’s the indexOf() method!