How to search for an array element in TypeScript?


In TypeScript, while working with the array, we often require to search for a particular element. To search for an element, either we can use the naive approach using the for loop or some built-in method such as the find() or indexOf() method.

Also, we will learn to find the particular object in the array based on the object property.

Using the for-of Loop to Search a Particular Element in The Array

The naive approach to searching for an element is using linear search. In linear search, we need to iterate through the array using the for loop and check for every element if it matches the searching element.

Syntax

Users can follow the syntax below to use the linear search to search for a particular element in the array.

let num_array: Array<number> = [
   23, 756, 232, 67, 099, 32, 1, 54, 87, 98, 321, 1, 12, 55, 6, 5,
];
let current: number = 0;
let searchElement: number = 6;
for (let num of num_array) {
   if (num === searchElement) {
      // element found
   }
   current++;
}

Algorithm

  • Step 1 − Define the current variable to keep track of the current index of the array and initialize it with zero.

  • Step 2 − Define the searchElement variable, and initialize it with the searching element.

  • Step 3 − Use the for-of loop to iterate through thenum_array.

  • Step 4 − Inside the for-of loop, use the if statement to check if the element at the current index matches the searchElement or not.

  • Step 5 − Increase the current by one after every iteration of the for-of loop.

Example

In this example, we have created the searchInArray() function to search for an element in the array. Inside the searchInArray() function, we have implemented the above algorithm of linear search.

// Array of various numbers
let num_array: Array<number> = [
   23, 6, 232, 6, 099, 32, 1, 54, 87, 98, 321, 1, 12, 55, 6, 5,
];
// current variable to keep track of the current index
let current: number = 0;

// element to search in the array
let searchElement: number = 6;
function searchInArray(searchElement: number) {

   // for-of loop to iterate through the array
   for (let num of num_array) {
      // if searchElement matches to the current element, print the index
      if (num === searchElement) {
         console.log("The " + searchElement + " is found at index " + current);
      }
      // increase the current by 1.
      current++;
   }
}
// calling the searchInArray function.
searchInArray(searchElement);
searchInArray(55);

On compiling, it will generate the following JavaScript code −

// Array of various numbers
var num_array = [
   23, 6, 232, 6, 099, 32, 1, 54, 87, 98, 321, 1, 12, 55, 6, 5,
]; 

// current variable to keep track of the current index
var current = 0;

// element to search in the array
var searchElement = 6;
function searchInArray(searchElement) {

   // for-of loop to iterate through the array
   for (var _i = 0, num_array_1 = num_array; _i < num_array_1.length; _i++) {

      var num = num_array_1[_i];
      // if searchElement matches to the current element, print the index
      if (num === searchElement) {
         console.log("The " + searchElement + " is found at index " + current);
      }
      // increase the current by 1.
      current++;
   }
}
// calling the searchInArray function.
searchInArray(searchElement);
searchInArray(55);

Output

The above code will produce the following output −

The 6 is found at index 1
The 6 is found at index 3
The 6 is found at index 14
The 55 is found at index 29

Using The find() Method to Search For an Element in The Array

The find() method is a built-in library method in TypeScript, which we can use to find an element in the array. The find() method takes the callback function as a parameter. The callback function returns true or false based on a certain condition.

When the callback function returns true for the first time, the find method returns that element.

Syntax

Users can follow the syntax below to find the element using the find() method from the array.

ref_array.find(callback_func);
function callback_func(element){
   // return true or false based on the value of the element
}

Parameters

  • callback_func − It is a function invoked for every element of the ref_array. It returns true or false.

Return Value

It returns the first element, which satisfies the callback function’s conditional statement.

Example

In the example below, we have created the array of objects containing the chir_id, chair_color, and chair_wheel. We use the find() method to search for a chair of green color. The callback function of the find() method returns true or false based on the chair_color property of an object.

// Creating the interface for the object
interface Obj {
   chair_id: number;
   chair_color: string;
   chird_wheel: number;
}
// creating the array of objects
let array_obj: Array<Obj> = [
   { chair_id: 1, chair_color: "blue", chird_wheel: 6 },
   { chair_id: 2, chair_color: "black", chird_wheel: 5 },
   { chair_id: 3, chair_color: "green", chird_wheel: 4 },
   { chair_id: 4, chair_color: "red", chird_wheel: 5 },
   { chair_id: 5, chair_color: "blue", chird_wheel: 6 },
];
// store searched object, returned from the find() method
let searched_obj: Obj | undefined = array_obj.find(callback_func);

// callback function returning the boolean value
function callback_func(object: Obj): boolean {

   // if the object color is green, return true; otherwise, return false for a particular object element
   if (object.chair_color == "green") {
      return true;
   }
   return false;
}
// Print the id of the searched object
console.log("The searched object is " + searched_obj.chair_id);

On compiling, it will generate the following JavaScript code −

// creating the array of objects
var array_obj = [
   { chair_id: 1, chair_color: "blue", chird_wheel: 6 },
   { chair_id: 2, chair_color: "black", chird_wheel: 5 },
   { chair_id: 3, chair_color: "green", chird_wheel: 4 },
   { chair_id: 4, chair_color: "red", chird_wheel: 5 },
   { chair_id: 5, chair_color: "blue", chird_wheel: 6 },
];
// store searched object, returned from the find() method
var searched_obj = array_obj.find(callback_func);

// callback function returning the boolean value
function callback_func(object) {

   // if the object color is green, return true; otherwise, return false for a particular object element
   if (object.chair_color == "green") {
      return true;
   }
   return false;
}
// Print the id of the searched object
console.log("The searched object is " + searched_obj.chair_id);

Output

The above code will produce the following output −

The searched object is 3

Using The indexOf() Method to Search For an Element in The Array

The indexOf() method takes an array element as a parameter rather than taking a callback function. It returns the index of the first occurrence of the element in the array.

Syntax

Users can follow the syntax below to use the indexOf() method to search for an element in the array.

let elementIndex: number = array.indexOf(element, startIndex);

Parameters

  • element − It is an element to search in the array.

  • startIndex − It is an optional parameter representing the starting index to search for an element in the array.

Return Value

It returns the index value of the first occurrence of the element in the array or -1 if the element doesn’t found.

Example

The below example demonstrates the use of the indexOf() method to find the first occurrence of the particular element in the array. We created the string array and found the particular string in the array using the indexOf() method.

let str_array: Array<string> = [
   "TutorialsPoint",
   "Hello",
   "TypeScript",
   "!",
   ".",
];
// using the indexOf() method.
let searched_index: number = str_array.indexOf("!");
console.log(
   "The first occurrence of the ! in the str_array is at index " + searched_index
);

On compiling, it will generate the following JavaScript code −

var str_array = [
   "TutorialsPoint",
   "Hello",
   "TypeScript",
   "!",
   ".",
];
// using the indexOf() method.
var searched_index = str_array.indexOf("!");
console.log("The first occurrence of the ! in the str_array is at index " + searched_index);

Output

The above code will produce the following output −

The first occurrence of the ! in the str_array is at index 3

We learned different approaches to searching for an element in the array. Also, we learned to search for a particular object in the object’s array using the find() method based on the particular object property.

Updated on: 03-Jan-2023

19K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements