"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Searching an Element in an Array with JavaScript

Searching an Element in an Array with JavaScript

Published on 2024-08-22
Browse:380

Searching an Element in an Array with JavaScript

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  0) {
  console.warn(`Element not found in current array!`);
}

Output: Element found at position 5

Steps

  1. Initialize array, searchElement, and count.
  2. Iterate through array using a for loop.
  3. Check if array[i] equals searchElement.
  4. If true, output the position and exit the loop.
  5. If the loop completes without finding the element, increment count.
  6. 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

  1. Initialize array, totalOccurrences, and searchElement.
  2. Iterate through array.
  3. Check if array[i] equals searchElement.
  4. If true, increment totalOccurrences.
  5. 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.

Release Statement This article is reproduced at: https://dev.to/vrajparikh/searching-an-element-in-an-array-with-javascript-2jmc?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3