How to get the index of an item in a JavaScript array

The following is the method to retrieve the item index in the JS array based on the value

Suppose you have the value of the item contained in the array and want to get its index.

How can you get it?

If the item is a primitive value (such as a string or number), you can useindexOfArray method:

const letters = ['a', 'b', 'c']

const index = letters.indexOf(‘b’)

//index is 1

Remember, the index starts with the number0

If the project is an object, you cannot use this method, because if you try to do this:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.indexOf({ letter: ‘b’, })

indexwill-1This means that the item cannot be found. Because objects are compared by reference rather than by value (different from the original type). Object passed toindexOfIt is a completely different object from the second item in the array.

you can use itfindIndexFor values like this, it will run a function for each item in the array, which will be passed to the element and its index. Return from which the return value will be assigned to the return valuefindIndex:

const letters = [
  {
    letter: 'a',
  },
  {
    letter: 'b',
  },
  {
    letter: 'c',
  },
]

const index = letters.findIndex((element, index) => { if (element.letter === ‘b’) { return true } })

//index is 1

Download mine for freeJavaScript beginner's manual


More js tutorials: