JavaScript Program to Search an Element in an Array
Last Updated :
12 Jun, 2024
A JavaScript program searches an element in an array by iterating through each item and comparing it with the target value. If found, it returns the index; otherwise, it returns -1, indicating absence.
Following are the ways to search for an element in an array:
Approach 1: Using Recursive Approach
The recursive approach in JavaScript for binary search involves dividing the array recursively until finding the target element or exhausting the search space, returning the element's index or -1 accordingly.
Example: The function recursively applies binary search to locate the target element within a sorted array, returning its index if found, or -1 if not present, with efficient time complexity.
JavaScript
function SearchingFunction(arr, target, low = 0, high = arr.length - 1) {
if (low > high) return -1;
let mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
else if (arr[mid] < target)
return SearchingFunction(arr, target, mid + 1, high);
else
return SearchingFunction(arr, target, low, mid - 1);
}
const array = [10, 20, 30, 40, 50, 60];
const targetElement = 30;
const result = SearchingFunction(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);
OutputThe index of 30
is: 2
Approach 2: Using Array.reduce() method
The binary search is implemented with Array.reduce() iterates through the array, accumulating results. It returns the index of the target element or -1 if not found, with linear time complexity.
Example: The function uses Array.reduce to search for the target element within an array, returning its index if found, or -1 if not present, with linear time complexity.
JavaScript
function SearchingFunction(arr, target) {
return arr.reduce((acc, val, index) => {
if (acc !== -1) return acc;
if (val === target) return index;
return -1;
}, -1);
}
const array = ["HTML", "CSS", "Javascript", "React", "Redux", "Node"];
const targetElement = "Redux";
const result = SearchingFunction(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);
OutputThe index of Redux is:
4
Approach 3: Using a for loop:
Using a for loop, iterate through the array elements, comparing each element to the target. If a match is found, return true; otherwise, return false after iterating through all elements.
Example: In this example The searchElement function iterates through an array to find a target element and returns its index if found, otherwise returns -1.
JavaScript
function searchElement(arr, target) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
const array = [10, 20, 30, 40, 50, 60];
const targetElement = 30;
const result = searchElement(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);
output:
The index of 30 is: 2
Approach 4: Using Array.indexOf():
To search an element in an array using `Array.indexOf()`, provide the element to search for as an argument. It returns the index of the first occurrence of the element, or -1 if not found.
Example: In this example we searches for the element "3" within the array using Array.indexOf(), returning its index. Output: 2 (indexing starts from 0).
JavaScript
let array = [1, 2, 3, 4, 5];
let searchElement = 3;
let index = array.indexOf(searchElement);
// Returns index 2 (indexing starts from 0)
console.log(index);
Approach 5: Using includes
Using the includes method, you can check if an array contains a specific element. This method returns true if the element is found and false otherwise. It provides a simple and readable way to verify the presence of an element within an array.
Example: in this example we are searching if certain elements present in array or not.
JavaScript
function searchElement(arr, element) {
return arr.includes(element);
}
console.log(searchElement([1, 2, 3, 4, 5], 3));
console.log(searchElement([1, 2, 3, 4, 5], 6));
Similar Reads
JavaScript Program to Search a Word in a 2D Grid of Characters In this article, we will solve a problem in which you are given a grid, with characters arranged in a two-layout(2D). You need to check whether a given word is present in the grid. A word can be matched in all 8 directions at any point. Word is said to be found in a direction if all characters match
7 min read
JavaScript Program to Find Common Elements Between Two Sorted Arrays using Binary Search Given two sorted arrays, our task is to find common elements in two sorted arrays then the program should return an array that contains all the elements that are common to the two arrays. The arrays can contain duplicate elements, that is, values at one index in an array can be equal to the values a
3 min read
JavaScript Program to Find the Distance Value between Two Arrays We will be given two integer arrays and an integer d. The task is to calculate the distance between the two given arrays based on the given integer value. The distance value will be calculated as the number of elements arr1[i] such that there is not any element arr2[j] where |arr1[i]-arr2[j]| <=
3 min read
Javascript Program for Search an element in a sorted and rotated array An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Exam
7 min read
Java Program to Print the Smallest Element in an Array Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. Example: arr1[] = {2 , -1 , 9 , 10} output : -1 arr2[] = {0, -10, -13, 5} output : -13 We need to find and print the smallest value
3 min read
Java Program to Search an Element in a Circular Linked List A linked list is a kind of linear data structure where each node has a data part and an address part which points to the next node. A circular linked list is a type of linked list where the last node points to the first one, making a circle of nodes. Example: Input : CList = 6->5->4->3->
3 min read
Java Program to Search an Element in Vector A vector in Java is a dynamic array that can be resized as needed. It is synchronized, which means it is safe in multi-threaded programs. To find an element in a Vector we have to loop through its elements to find a match. In this article, we will learn how to search for a component in a Vector usin
3 min read
Java Program to Print the kth Element in the Array We need to print the element at the kth position in the given array. So we start the program by taking input from the user about the size of an array and then all the elements of that array. Now by entering the position k at which you want to print the element from the array, the program will print
2 min read
Binary search in an object Array for the field of an element What is Binary Searching?Binary searching is a type of algorithm that can quickly search through a sorted array of elements. The algorithm works by comparing the search key to the middle element of the array. If the key is larger than the middle element, the algorithm will search the right side of t
8 min read
Searching Elements in an Array | Array Operations In this post, we will look into search operation in an Array, i.e., how to search an element in an Array, such as: Searching in an Unsorted Array using Linear SearchSearching in a Sorted Array using Linear SearchSearching in a Sorted Array using Binary SearchSearching in an Sorted Array using Fibona
15+ min read