TypeScript Array some()
Syntax & Examples
Array.some() method
The some() method tests whether at least one element in the array passes the test implemented by the provided callback function. It returns a Boolean value.
Syntax of Array.some()
The syntax of Array.some() method is:
some(callbackfn: function, thisArg?: any): boolean
This some() method of Array determines whether the specified callback function returns true for any element of an array.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
callbackfn | required | A function to test for each element, taking three arguments: the current element, the index of the current element, and the array being traversed. |
thisArg | optional | Value to use as this when executing callbackfn. |
Return Type
Array.some() returns value of type boolean
.
✐ Examples
1 Using some() to test for values greater than a number
The some() method can be used to check if any elements in the array are greater than a specified number.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4, 5]. - Define a callback function that checks if an element is greater than 3.
- Use
some(callbackfn)
to test if any elements are greater than 3. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 2, 3, 4, 5];
const result = arr.some(element => element > 3);
console.log(result);
Output
true
2 Using some() to test for even numbers
The some() method can be used to check if any elements in the array are even.
For example,
- Create an array
arr
with numeric values [1, 3, 5, 7, 8]. - Define a callback function that checks if an element is even.
- Use
some(callbackfn)
to test if any elements are even. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = [1, 3, 5, 7, 8];
const result = arr.some(element => element % 2 === 0);
console.log(result);
Output
true
3 Using some() to test for presence of a specific element
The some() method can be used to check if a specific element exists in the array.
For example,
- Create an array
arr
with string values ['apple', 'banana', 'cherry']. - Define a callback function that checks if an element is 'banana'.
- Use
some(callbackfn)
to test if 'banana' is present in the array. - Store the result in
result
. - Log
result
to the console.
TypeScript Program
const arr = ['apple', 'banana', 'cherry'];
const result = arr.some(element => element === 'banana');
console.log(result);
Output
true
Summary
In this TypeScript tutorial, we learned about some() method of Array: the syntax and few working examples with output and detailed explanation for each example.