Searching an Element in an Array with JavaScript

WBOY
Release: 2024-08-08 15:46:20
Original
176 people have browsed it

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 <= 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!`); }
Copy after login

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}`);
Copy after login

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.

The above is the detailed content of Searching an Element in an Array with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!