Check if an element is present in an array using JavaScript
Last Updated :
12 Jul, 2024
Checking if an element is present in an array using JavaScript involves iterating through the array and comparing each element with the target value. If a match is found, the element is considered present; otherwise, it's absent.
There are different approaches to finding an element present in an array, which is described below:
Using includes() method
This method can be utilized to find whether a particular element is present in the array or not. it returns true or false i.e., If the element is present, then it returns true otherwise false.
Example: In this example, the array is declared and by using the includes() method, & we can check the value present in the array.
JavaScript
// Define an array
const arr = [21, 12, 13, 45, 54];
// Check if the array includes the value 12
if (arr.includes(12)) {
console.log("12 is present in the array.");
} else {
console.log("12 is not present in the array.");
}
Output:
12 is present in the array
Using the indexOf() method
This method can be used to find the index of the first occurrence of the search element provided as the argument to the method.
Example: In this example, an array is declared and by using indextOf() function, we can check the value present in the array.
JavaScript
// Define an array
const arr = [10, 72, 3, 14, 5];
// Check if the array includes the value 3
if (arr.indexOf(3) >= 0) {
console.log("3 is present in the array.");
} else {
console.log("3 is not present in the array.");
}
Output:
3 is present in the array
Using the find() method
This method is used to get the value of the first element in the array that satisfies the provided condition. It checks all the elements of the array and whichever the first element satisfies the condition is going to print.
Example: In this example, an array is declared, and by using the find() function, we can check the value present in the array.
JavaScript
// Define an array
const arr = [5, 20, 30, 40, 50];
// Use the find() method to check if the
// value 30 is present in the array
const result = arr.find(element => element === 30);
// Check the result and log a message
if (result !== undefined) {
console.log("30 is present in the array.");
} else {
console.log("30 is not present in the array.");
}
Output:
30 is present in the array
Using the for() Loop
The for loop facilitates the execution of a set of instructions repeatedly until some condition evaluates and becomes false.
Example: In this example, an array is declared by using for() loop iteration up to the element found. By using this, we can check whether the value present in the array or not.
JavaScript
// Define an array
const array1 = [13, 23, 33, 43, 53];
// Initialize a flag variable
let p = false;
// Iterate through the array and check each element
for (let i = 0; i < array1.length; i++) {
if (array1[i] === 53) {
p = true;
break;
}
}
// Check the flag variable and log a message
if (p) {
console.log("53 is present in the array.");
} else {
console.log("53 is not present in the array.");
}
Output:
53 is present in the array
Using the Array.some() method
Algorithm:
- Initialize the array.
- Use some method on for loop with some condition which matches the required element and returns true if matches.
- Print the evaluated result.
Example: By using some(), we can check the value present in the array or not.
JavaScript
// Define an array
const arr = [5, 20, 30, 40, 50];
// Use the some() method to check if the
// value 30 is present in the array
const result = arr.some(element => element === 30);
// Check the result and log a message
if (result !== undefined) {
console.log("30 is present in the array.");
} else {
console.log("30 is not present in the array.");
}
Output:
30 is present in the array.
Time complexity: O(N), Where N is the length of the Array.
Auxiliary complexity: O(1), Because no extra space is used.
Using a filter() method
Using the filter() method in JavaScript, you can check if an element is present in an array by filtering the array for the element and then checking if the resulting array's length is greater than zero. This approach is efficient and concise.
Example:
JavaScript
const arr = [1, 2, 3, 4, 5];
const checkElement = (array, element) => array.filter(el => el === element).length > 0;
const isThreePresent = checkElement(arr, 3);
const isEightPresent = checkElement(arr, 8);
console.log(isThreePresent); // true
console.log(isEightPresent); // false
Using Set for Efficient Element Checking
The Set object in JavaScript stores unique values of any type, including primitive types and object references. By converting the array into a Set, we can take advantage of its quick lookup capabilities using the has() method.
Example: Using a Set for checking element presence in an array provides an elegant and efficient solution, enhancing code readability and performance compared to traditional iteration-based methods. It's a modern approach that leverages JavaScript's built-in data structures for optimal results.
JavaScript
// Define an array
const arr = [1, 2, 3, 4, 5];
// Convert the array into a Set
const set = new Set(arr);
// Function to check if an element exists in the array
const isElementPresent = (array, element) => set.has(element);
// Usage examples
console.log(isElementPresent(arr, 3)); // true
console.log(isElementPresent(arr, 8)); // false
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
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
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ 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
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 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