Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
communitycreator

What is the array.indexOf() method in TypeScript?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The indexOf() method is used to return the index position of the first match of a value in an array in TypeScript, as well as in JavaScript. This method returns an integer value. However, if the element does not exist in the array, then the method returns -1.

Syntax

array.indexOf(element)
Syntax of the "indexOf()" method in TypeScript

Parameter value

element: This is the element whose index we want to get.

Return value

The index of the first matching element, which is an integer, in the array is returned. If no such element exists, then a -1 integer value is returned.

Example

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>;
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
// get and print index of some elements
console.log(names.indexOf("Theodore"))
console.log(names.indexOf("James"))
console.log(numbers.indexOf(10000))
console.log(numbers.indexOf(0.9))
console.log(cars.indexOf("TOYOTA"))
Get the index of an element in TypeScript

Explanation

  • Lines 2–5: We create some arrays in TypeScript.
  • Lines 8–12: We get the index of some elements that exist and some that do not exist. Then, we print the results to the console.
Note: In line 12, the method returns -1 because "TOYOTA" is not present in the array "Toyota".

RELATED TAGS

typescript
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring