TypeScript – How to Find Element in Array

JavaScript provides various methods to find elements in the array. We can use these methods in TypeScript as well. In this tutorial, we will go through each method separately and understand its usage with an example.

const marks = [90, 44, 76, 12, 0, 34];

function checkPass(mark) {
    return mark > 35;
}

function checkPassAndPrint(mark) {
    if (checkPass(mark)) {
        console.log(mark);
    }
}

const filteredMarks = marks.filter(checkPass);      // [90, 44, 76] - All matching elements
const foundMark = marks.find(checkPass);            // 90 - First Matched element
const foundIndex = marks.findIndex(checkPass);      // 0 - Index of First Matched element
const indexOfZero = marks.indexOf(0);               // 4 - Array index of the specified element
const includesZero = marks.includes(0);             // true - Arrays contains the specified element
const somePass = marks.some(checkPass);             // true - At least one element passes the condition

marks.forEach(checkPassAndPrint); // Prints: 90 44 76 - Execute the function for each element

We can also find an object by property value using these methods. We only need to change the property value check code in the checkPass method.

const people = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 17 },
  { name: "Charlie", age: 30 },
  { name: "David", age: 15 }
];

// 1. Using filter function

function isAdult(person) {
    return person.age > 18;
}

// [{ name: "Alice", age: 25 }, { name: "Charlie", age: 30 }]
const adults = people.filter(isAdult);

// 2. Using an inline arrow function

const isAdult = (person: { age: number }) => person.age > 18;

// [{ name: "Alice", age: 25 }, { name: "Charlie", age: 30 }]
const adults = people.filter(person => person.age > 18);   

1. Methods to Find Elements in an Array

At a high level, we can use one of the following methods to find an element or element index in the array.

MethodDescription
filter()Returns an array of elements that satisfy the given filter expression/function.
find()Returns the first element that satisfies the specified boolean function, or undefined if no elements are found.
findLast()Returns the last element that satisfies the specified function, similar to find().
findIndex()Returns the index of the first element that satisfies the specified boolean function, or -1 if no match is found.
findLastIndex()Returns the last index of the element that satisfies the specified function, similar to findIndex().
indexOf()Returns the first index of a given element, or -1 if the value is not found.
lastIndexOf()Returns the last index of a given element.
includes()Returns true if the array contains the given value, otherwise returns false.
some()Returns true if at least one element satisfies the given boolean function, otherwise returns false.
forEach()Executes a given function for each element in the array.

2. Array.filter() – Get All Elements matching a Condition

The filter() method executes a given function against each element in the array and returns a new array containing elements that satisfy the given function.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • defining a boolean-valued function checkPass() that takes marks as a parameter and returns if marks are greater than pass marks 35.
  • applying checkPass() for each element in the marks array using the filter() method.
// array of student marks in different subjects
const marks = [90, 44, 76, 12, 0, 34]

// function to check if student passed or not for a subject
function checkPass(mark){
    return mark > 35
}

// usage of filter method
console.log( marks.filter(checkPass) )   //[ 90, 44, 76 ]

3. Array.find() – Find an Element matching a Condition

The find() method executes a function for each element in the array and returns the first element that satisfies the function, while findLast() method returns the last element that satisfies the function.

The find() and findLast() returns undefined if no elements are found.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • declaring and defining a function checkPass() that takes marks as a parameter and returns if marks are greater than pass marks(35).
  • finding the first element/marks that satisfy the given function using the method find().
  • finding the last element/marks that satisfy the given function using the method findLast().
// array of student marks in different subjects
const marks = [90, 44, 76, 12, 0, 34]

// function to check if student passed or not for a subject
function checkPass(mark){
    return mark > 35
}

// usage of find method
console.log( marks.find(checkPass) )  //90

// usage of findLast method
console.log( marks.findLast(checkPass) )  //76

4. Array.findIndex() – Find Index of Element matching a Condition

The findIndex() executes a given function against each element in the given array and returns the index of the first element that satisfies the given function, while findLastIndex() returns the index of the last element that satisfies the given function.

The findIndex() and findLastIndex() methods return -1 if no match is found.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • declaring and defining a function checkPass() that takes marks as a parameter and returns if marks are greater than pass marks(35).
  • finding the index first element/marks that satisfy the given function using the method findIndex().
  • finding the index last element/marks that satisfy the given function using the method findLastIndex().
// array of student marks in different subjects
const marks = [90, 44, 76, 12, 0, 34]

// function to check if student passed or not for a subject
function checkPass(mark){
    return mark > 35
}

// usage of findIndex method
console.log( marks.findIndex(checkPass) )  //0

// usage of findLastIndex method
console.log( marks.findLastIndex(checkPass) )  //2

Here 0 is the index of the element 90 and 2 is the index of the element 76.

5. Array.indexOf() – Find Element Index by Element Value

The indexOf() starts the search from left to right and returns the index of the first element that matches the specified element, while lastIndexOf() returns the index of the last element that matches the given element.

The indexOf() and lastIndexOf() methods return -1 if no match is found.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • finding the index of the first element that matches the given element using the indexOf() method.
  • finding the index of the last element that matches the given element using the lastIndexOf() method.
// array of student marks in different subjects
const marks = [90, 44, 0, 12, 0, 34]

// usage of indexOf method
console.log( marks.indexOf(0) )  //2

// usage of lastIndexOf method
console.log( marks.lastIndexOf(0) )   //4

where 2 is the index of the first occurrence of the element 0, and 4 is the index of the last occurrence of the element 0.

6. Array.includes() – Check if Element exists by Element Value

The includes() starts the search from left to right of an array and returns true if an element matches the given value else returns false.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • checking if the given element exists or not in the given array using the includes() method.
// array of student marks in different subjects
const marks = [90, 44, 0, 12, 0, 34]  

// usage of includes method
console.log( marks.includes(0) )        //true
console.log( marks.includes(100) )   //false

7. Array.some() – Check if an Element exists matching a Condition

The some() function executes a function against each element in the given array and returns true if at least one element satisfies the given function else returns false if no elements satisfy the given function.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • declaring and defining the function match() which returns a boolean value based on the input and condition. Here we check if the given mark value is equal to 0 or not.
  • checking if the given element exists in the array marks using the method some() which accepts match as a callback function.

The some() executes the match() against each mark in the array marks and returns true if at least one element/mark matches 0.

// array of student marks in different subjects
const marks = [90, 44, 0, 12, 0, 34]

// function to check for a match
function match(mark){
    return mark == 0
}

// usage of some method
console.log( marks.some(match) )  //true

8. Array.forEach() – Custom Logic

The forEach() executes the given function against each element. We can write custom logic to perform on the elements that match the given element.

In the following example, we are:

  • declaring an array of student marks in different subjects.
  • declaring and defining the function match that prints the element that matches the given condition. Here we check if the given mark is equal to 0 then print the current mark.
  • executing the match() function against each element in the array marks using the method forEach().
// array of student marks in different subjects
const marks = [90, 44, 0, 12, 0, 34]

// function to check for a match
function match(mark){
    if(mark == 0)
        console.log(mark)
}

// usage of forEach method
marks.forEach(match)

9. Conclusion

In this tutorial, we have learned different ways of finding an element in the given array using an inbuilt method or writing our own custom logic using examples. Apply a method according to the use case and find the element that we need in the given array.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode