EN
TypeScript - get index of item in array
0 points
In this article, we would like to show you how to get the index of item in an array in TypeScript.
Quick solution:
xxxxxxxxxx
1
const numbers: number[] = [1, 2, 3];
2
3
const result = numbers.indexOf(2);
4
console.log(result); // 1
In this example, we use indexOf()
method to find the index of the specific item in the numbers
array.
xxxxxxxxxx
1
const numbers: number[] = [1, 2, 3];
2
3
console.log(numbers.indexOf(1)); // 0
4
console.log(numbers.indexOf(2)); // 1
5
console.log(numbers.indexOf(5)); // -1
Output:
xxxxxxxxxx
1
0
2
1
3
-1
Example with an array of strings:
xxxxxxxxxx
1
const letters: string[] = ['A', 'B', 'C'];
2
3
console.log(letters.indexOf('A')); // 0
4
console.log(letters.indexOf('B')); // 1
5
console.log(letters.indexOf('X')); // -1
Output:
xxxxxxxxxx
1
0
2
1
3
-1
Note:
If the specified value is not present in the array, the
indexOf()
method returns-1
.