How to check a string data type is present in array using JavaScript ?
In JavaScript, an array is a collection of data that can be of the same or different type. If we have the array containing the data, our task is to identify if it is a string data type. In this article, we will learn how to use the typeof operator.
Syntax:
typeof value
Note: The typeof operator returns a string indicating the type of the operand.
Example 1:
Input:
const sample = “GeeksforGeeks”;
console.log(typeof sample);
Output : string
Example 2:
Input:
const sample = 369;
console.log(typeof sample);
Output : number
Example 3:
Input:
const sample = true;
console.log(typeof sample);
Output : boolean
Approach:
- Iterate over the whole array to check if each element is a string or we will do it using for loop.
- We will compare the type of iterator element with the ‘string’ data type using the if block.
- If block will execute if it encounters the string data type.
- When there is no string value present, else block will get executed.
Example 1: The following code demonstrates the case where the string is present.
Javascript
<script>
const arr = [1,2,3, "Geeks" ,4];
let flag = 0;
for (let i of arr){
if ( typeof i == 'string' ){
console.log( "String found" );
flag = 1;
}
}
if (flag==0){
console.log( "String not found" );
}
</script>
|
Output:
String found
Example 2: The following code demonstrates the case where the string is absent.
Javascript
<script>
const arr = [1,2,3,4,5];
let flag = 0;
for (let i of arr){
if ( typeof i == 'string' ){
console.log( "String found" );
flag = 1;
}
}
if (flag==0){
console.log( "String not found" );
}
</script>
|
Output:
String not found
We can identify any data type using the typeof operator. We can use it for other data types like eg. numbers, boolean, etc.
Approach 2: Using Array.some() and instanceof:
- Initialize the Array.
- Use Some method on the Array which checks the instance of each element and returns true if any string is present.
- Print Evaluated result.
Example: The following code demonstrates the case where the string is present.
Javascript
const arr = [1, 2, "GFG" , 4, 5];
let flag = arr.some(x => x instanceof String);
if (flag) {
console.log( "String not found" );
}
else {
console.log( "String found" )
}
|
Output:
String found
Time complexity: O(N), Where N is the length of the Array.
Auxiliary complexity: O(1), Because no extra space is used.
Last Updated :
25 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...