Categories
Snippets

Array.indexOf()

Using the indexOf() call in javascript allows you to…

  1. Get the index of the Array item you pass across
  2. Check to see if an item exists within an Array

If we have the following Array

var family = ['Justin', 'Laura', 'Noah', 'Darcey'];

we can then pass that array into the indexOf() function to find the index values.

family.indexOf('Justin'); // returns 0
family.indexOf('Laura'); // returns 1
family.indexOf('Noah'); // returns 2
family.indexOf('Darcey'); // returns 3

I can check to see if a value is contained within the Array by checking what the value of idexOf() returns. If the item does not exist within the Array it will return -1.

family.indexOf('Mark'); // returns -1

You can check this by putting in an IF statement with the check…

if (family.indexOf('Mark') === -1 {
  console.log('Mark is not part of the family')
} else {
  console.log('Mark is part of the family')
});

Side note

Thanks to Dan Needham for pointing out that I needed if (family.indexOf('Mark') === -1 instead of if (family.indexOf('Mark') = -1

Leave a Reply

Your email address will not be published. Required fields are marked *