Typescript find object in array

Typescript find object in array

Last updated: Jan 20, 2023
Reading time · 3 min

banner

# Table of Contents

# Find the first object in an array that matches a condition in TS

To find an object in an array:

  1. Use the Array.find() method to iterate over the array.
  2. Check if each object meets a condition.
  3. The find method will return the first matching object.
Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; const found = arr.find((obj) => return obj.id === 1; >); // 👇️ console.log(found);

The function we passed to the Array.find method gets called with each element (object) in the array until it returns a truthy value or iterates over the entire array.

On each iteration, we check if the id property of the object is equal to 1 .

This is very convenient when you only need to get the first object that matches the specific condition.

There are no wasted iterations because once the condition is met, the find() method short-circuits and returns the object.

If the callback function we passed to the find method never returns a truthy value, the find() method returns undefined .

Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; // 👇️ const found: | undefined const found = arr.find((obj) => return obj.id === 1; >);

Notice that the type of the found variable is either an object or undefined .

You can use a type guard to narrow down the type to be able to access properties on the object.

Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; // 👇️ const found: | undefined const found = arr.find((obj) => return obj.id === 1; >); if (found) // ✅ TypeScript now knows that found is an object // and not undefined console.log(found.country); // 👉️ Mexico >

TypeScript can safely infer the type of the found variable to be an object in the if block.

# Find all Objects in an Array that match a condition in TS

To find all objects in an array that match a condition:

  1. Use the filter() method to iterate over the array.
  2. Check if each object matches a condition.
  3. The filter method will return a new array containing the objects that match the condition.
Copied!
const arr = [ id: 1, country: 'Mexico' >, id: 2, country: 'Germany' >, id: 3, country: 'Mexico' >, ]; const filtered = arr.filter((obj) => return obj.country === 'Mexico'; >); // 👇️ [, ] console.log(filtered);

The function we passed to the Array.filter method gets called with each element (object) in the array.

The filter() method returns a new array that only contains the elements that meet the condition.

Note that the filter method will iterate over the entire array, regardless of how many times the condition is met.

This way, we are able to get multiple objects that meet a specific condition from an array of objects.

If the callback function we passed to the filter method never returns a truthy value, the filter method returns an empty array.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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 = [ 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 = [ 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 = [ < 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 −

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 = [ "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.

Источник

How To Find An Object In An Array In Typescript

How to find an Object in an Array in TypeScript

Knowing how to find an object in an array in Typescript will be very useful for you when working with an object array, like working with data that is constructed in object type. So how to do it? Let’s go into detail now.

How to find an object in an array in TypeScript

Use loop method

Using the loop method, I will loop over the array and then make a condition to check if the object element is what I want. Then, It will execute the code.

type infor = < name: string; age: number; >; const objArray: infor[] = [ < name: "Mana", age: 18 >, < name: "Toma", age: 39 >, < name: "Waki", age: 22 >, < name: "Santo", age: 10 >, < name: "James", age: 29 >, < name: "Bitgaram", age: 18 >, < name: "Hani", age: 22 >, < name: "Jack", age: 25 >, < name: "Messi", age: 29 >, ]; // Function loop over the array, // then check if the type property is equal to the property in each object of the array function findObj( arr: Array>, obj: < name: string; age: number >) < for (let i = 0; i < arr.length; i++) < if (arr[i].name === obj.name && arr[i].age === obj.age) < console.log(obj); >> > findObj(objArray, < name: "Santo", age: 10 >);

Here I create a function to help you to find the object, and I use the most basic loop, which is for..loop. Just notice that object is a reference type, meaning you cannot compare two objects in a usual way. So I compare two objects by their properties. I highly recommend you create a unique property, like a critical property, that helps you easier when finding the object.

type infor = < id: number; name: string; age: number; >; const objArray: infor[] = [ < id: 1, name: "Toma", age: 39 >, < id: 2, name: "Waki", age: 22 >, < id: 3, name: "Santo", age: 10 >, < id: 4, name: "James", age: 29 >, < id: 5, name: "Bitgaram", age: 18 >, < id: 6, name: "Hani", age: 22 >, < id: 7, name: "Jack", age: 25 >, < id: 8, name: "Messi", age: 29 >, < id: 9, name: "Mana", age: 18 >, ]; // Function loop over the array, // then check if the id property equal with id property of the object function findObj(arr: infor[], id: number) < for (let i = 0; i < arr.length; i++) < if (arr[i].id === id) < console.log(arr[i]); >> > findObj(objArray, 5); findObj(objArray, 8); findObj(objArray, 9);

You can also use any loop method like map or forEach with this logic to manually find the object in the object array.

Use find method

The find() method will help you search for the first element of your array that matches your condition. The find method will return the first object that satisfies the condition.

  • callback: The callback will be called each loop time.
  • element: Indicate the current element of the loop.
  • index: The index of the current element.
type infor = < id: number; name: string; age: number; >; const objArray: infor[] = [ < id: 1, name: "Toma", age: 39 >, < id: 2, name: "Waki", age: 22 >, < id: 3, name: "Santo", age: 10 >, < id: 4, name: "James", age: 29 >, < id: 5, name: "Bitgaram", age: 18 >, < id: 6, name: "Hani", age: 22 >, < id: 7, name: "Jack", age: 25 >, < id: 8, name: "Messi", age: 29 >, < id: 9, name: "Mana", age: 18 >, ]; // Return the object if the id property equals 1 const obj = objArray.find((ele, index) => < return ele.id == 1; >); console.log(obj);

Here by using the find method, I can return the object in the object array that satisfies the condition that id equals 2.

Summary

In this article, I showed you how to find an object in an array in Typescript. You can manually use the loop method to do it or the find method to compare and return that object. Good luck for you!

Maybe you are interested:

Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.

Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm

Источник

Читайте также:  Get class field value java
Оцените статью