Searching an Element in an Array with JavaScript
Vraj Parikh
Posted on August 8, 2024
Linear Search
Linear search is a simple method to find an element in an array by checking each element sequentially.
Example
let data = [41, 23, 63, 42, 59];
const searchingElement = 59;
let count = 0;
for (let i = 0; i <= data.length; i++) {
if (data[i] === searchingElement) {
console.log(`Element found at position ${i + 1}`);
break;
} else if (i === data.length) {
count++;
}
}
if (count > 0) {
console.warn(`Element not found in current array!`);
}
Output: Element found at position 5
Steps
- Initialize
array
,searchElement
, andcount
. - Iterate through
array
using afor
loop. - Check if
array[i]
equalssearchElement
. - If true, output the position and exit the loop.
- If the loop completes without finding the element, increment
count
. - After the loop, if
count
is greater than 0, output a not found message.
Counting Occurrences
To count occurrences of an element:
let data = [41, 23, 63, 42, 59, 23];
let totalOccurrences = 0;
const searchingElement = 63;
for (const i in data) {
if (data[i] === searchingElement) {
totalOccurrences++;
}
}
console.log(`Total occurrences of ${searchingElement} is ${totalOccurrences}`);
Output: Total occurrences of 63 is 1
Steps
- Initialize
array
,totalOccurrences
, andsearchElement
. - Iterate through
array
. - Check if
array[i]
equalssearchElement
. - If true, increment
totalOccurrences
. - Output the total occurrences.
Linear search is straightforward but not the most efficient for large datasets. Advanced algorithms like binary search can be more efficient for sorted arrays.
💖 💪 🙅 🚩
Vraj Parikh
Posted on August 8, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.