How to find if an array contains a specific string in JavaScript/jQuery ?
Last Updated :
31 Jul, 2024
In order to Check if an array contains a specific string be done in many ways in Javascript. One of the most common methods to do this is by using the traditional for loop. In Javascript, we have several other modern approaches which help in finding a specific string in an array to iterate the array some more methods include using the indexOf() method and includes()method and with the help of jQuery we have grep() method. In this article, we will explore these approaches with their example.
Approach 1: Using the indexOf() method
It is an inbuilt javascript method that returns the index of the first occurrence of the string to be searched which returns 1 if found and -1 if not found
Syntax:
array.indexOf(searchValue , index)
- searchValue: It is the value that we need to search in the array.
- Index: It is the index position to start searching in the array. If not specified, the search will start from index 0.
Example: In this example, we create an array of strings and a variable to store the search string and then we use the index of the method to look for the specific string in the array if the string is present in the array it returns 1, and if it is not present it return -1.
JavaScript
const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Geeks';
if (array.indexOf(String) !== -1) {
console.log(`${String} is present in the array`);
} else {
console.log(`${String} is not present the array`);
};
Output:
Geeks is present in the array
Approach 2: Using the includes() method
It is a built-in method that returns a boolean value that indicates whether the string is present in the array or not. Here we will use it to check if a string is present in the array.
Syntax:
array.includes(searchValue, index);
Parameters:
- searchValue: It is the value that we need to search in the array.
- Index: It is the index position to start searching in the array. If not specified, the search will start from index 0.
Example: In this example, we will use the array includes() method to check whether the string is present in the array if the string is present in the array it returns 1, and if it is not present it returns -1 and prints the required output in the console.
JavaScript
const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Computer science';
if (array.includes(String) !== -1) {
console.log(`${String} is present in the array`);
} else {
console.log(`${String} is not present the array`);
};
Output:
Computer science is present in the array
Approach 3: Using a for loop
We can iterate through the array using a for loop and check each element to see if it matches the search string and when it matches the string we break the loop and print the answer in the console.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, we will iterate over the elements of an array using the for loop and will search for the required string in the array when the string is found the loop will break and we will print the output in the console.
JavaScript
const array = ['Geek', 'Geeks', 'Geeksforgeeks', 'Computer science'];
const String = 'Geeksforgeeks';
let found = false;
for (let i = 0; i < array.length; i++) {
if (array[i] === String) {
found = true;
break;
}
}
if (found) {
console.log(`${String} is present in the array`);
} else {
console.log(`${String} is not present the array`);
};
Output:
Geeksforgeeks is present in the array
Approach 4: Using grep() Method
This is a built-in function that filters out the array based on the condition it uses the filter function to filter out the specific condition and it does not affect the original array.
Syntax:
grep( array, function [, invert ] );
Parameters:
- array: The array in which the search will be performed.
- function: The function used to test each element of the array
- invert: this method if true returns the elements of the array that do not satisfy the condition of the test.
Example: In this example, we will be creating an array with values in it and a value to be searched and we will use the grep() method to search for specific strings in the array by applying a condition that will return the first matched string.
HTML
<!DOCTYPE html>
<html>
<head>
<title>
JQuery | inArray() and grep() Method
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GFG Website
</h1>
<p id="up"></p>
<button onclick="runGrep()">
Search value
</button>
<p id="down"
style="color:green;"></p>
<script>
// Define variables
var elUp = document.getElementById("up");
var elDown = document.getElementById("down");
var arr = ["GFG", "GeeksForGeeks", "Geeks", "Geek"];
var value = "GeeksForGeeks";
// Update HTML content
elUp.innerHTML = "Click the button to search the array.<br>"
+ "Array: [" + arr + "]<br>"
+ "Search value: '" + value + "'";
// Define grep() search function
function runGrep() {
var result = $.grep(arr, function (element) {
return element === value;
});
if (result.length > 0) {
elDown.innerHTML = "Found: " + result[0];
} else {
elDown.innerHTML = "Not found";
}
}
</script>
</body>
</html>
Output:
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read