How To Check If An Array Contains A Value In Typescript

Typescript has many ways to check if an element exists in an array. Now, let’s follow three ways to check if an array contains a value in typescript.

Check if an array contains a value in Typescript

Method 1: Includes() method

Syntax: 

array.includes(value)

Parameter:

In Typescript(JS), includes() method determines whether the array includes an actual value among its entries, returning true or false.

For example:

// Create an array
const arrayForChecking = [2, 4, 6];
let found = arrayForChecking.includes(4);

if(found === true){
   console.log("has contained in array");
}
else {
   console.log("has not contained in array");
}

Console Output:

"has contained in array"

Include() method works a case-sensitive search to determine and find a string that exists in an array or not, returning true or false as appropriate. In the program, “4” exists at arrayForChecking[2]. Therefore include() will return true and the “If” function will return the True condition.

Method 2: Some() Method

Syntax:

array.some(function(value, index, arr), this)

Example:

const letter = ["a","b","c","d","e"];
const foundLetter = letter.some(letter => letter === 'b'); // true
const foundAnotherLetter = letter.some(letter => letter === 'h'); // false

if(foundLetter === true){
  console.log("The letter has been found");
}
else {
  console.log("The letter hasn't been found");
}
 
if(foundAnotherLetter === true){
  console.log("The letter has been found");
}
else {
  console.log("The letter hasn't been found");
}

Console Output

The letter has been found // index.ts:7
The letter hasn't been found // index.ts:17

some() method checks all elements of an array if any element passes a condition and returns true if one of the arrays passes a condition and stops finding. Executes callback function once each array element. Returns false if the function returns false for all of the array elements.

Method 3: Find() Method

Similar to some() method, find() also checks all elements in the array BUT if one of the elements in array passes condition, find() method will return a Value not a boolean like some() method.

For instance:

const letter = ["a","b","c","d","e"];
const found = letter.find(letter => letter === 'b'); 
console.log(found);

Console Output:

"b"

Summary

To check if an array contains a value in typescript, I showed you three ways to check it. I hope you understand and make them in your project. If you want to know more methods about an array in TS/JS, this guide can show all methods you need. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *