Languages
[Edit]
EN

JavaScript - get index of item in array

0 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you how to get the index of item in an array in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const numbers = [1, 2, 3];

const result = numbers.indexOf(2);
console.log(result);  // 1

Note:

If the specified value is not present in the array, the indexOf() method returns -1.

 

1. Practical example

In this example, we use indexOf() method to find the index of the specific item in the numbers array.

// ONLINE-RUNNER:browser;

const numbers = [1, 2, 3];

console.log(numbers.indexOf(1));  // 0
console.log(numbers.indexOf(2));  // 1
console.log(numbers.indexOf(5));  // -1

Example with an array of strings:

// ONLINE-RUNNER:browser;

const letters = ['A', 'B', 'C'];

console.log(letters.indexOf('A'));  // 0
console.log(letters.indexOf('B'));  // 1
console.log(letters.indexOf('X'));  // -1

2. Working with objects

In this example, we use findIndex() method to find the index of the specific item in the array of objects which name property value is equal to 'b'.

// ONLINE-RUNNER:browser;

const array = [
    { id: 1, name: 'a' },
    { id: 2, name: 'b' },
    { id: 3, name: 'c' }
];

const index = array.findIndex((object) => object.name === 'b');

console.log(index); // 1

 

See also

  1. JavaScript - find object by id in array of objects

  2. JavaScript - find indexes of all occurrences of element in array

References

  1. Array.prototype.indexOf() - JavaScript | MDN

Alternative titles

  1. JavaScript - get index of object inside array matching condition
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join