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 Target Value in a Rotated Array
In this article, we are going to implement a JavaScript program to Search for a target value in a rotated array. Table of Content Using Binary SearchUsing Linear SearchUsing Recursive FunctionUsing Modified Binary Search with Pivot Detection Using Binary SearchIn this approach, we begin by locating
5 min read
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 to find the Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array. Methods to Find the Index of the Last Occurrence of the Target Element in the Sorted ArrayUsin
4 min read
JavaScript Program for Binary Search using Recursion
In this article, we will demonstrate the Binary Search in JavaScript using the Recursive approach. Binary Search is a searching technique that works on the Divide and Conquer approach. It is faster than the linear search. It only works for the sorted arrays. It takes in O(log n) time for execution.
2 min read
JavaScript Program to Find Index of an Object by Key and Value in an Array
Finding the index of an object by key and value in an array involves iterating through the array and checking each object's key-value pair. Once a match is found, its index is returned. If no match is found, -1 is returned.Example:arr = [ { course: "DevOps", price: 11999 }, { course: "GATE", price:
6 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