DEV Community

stuxnat
stuxnat

Posted on

2 2

JavaScript Search Functions

This past week, I did an exercise that tested my skills in searching and filtering through arrays.

Here are several ways to do that in JS:

1. filter() function
The filter function can be used on arrays, and most data structures. Calling filter() returns a new filtered array.

2. find() function
Find is similar to filter, but will return only one element that matches a condition. If an element is not found, find() will return undefined.

3. includes()
The includes() function can be used to check if an array contains certain elements. This will return a true or false value.

4. for-loop
Using a for-loop versus a JavaScript function is great for being able to add more functionality once the search condition is met. In a for-loop, a new array will hold the elements that match the conditions. It will generally look something like this:

const array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
 const results = [];
 const count = 0;

 for (const i = 0; i < 10; i++) {
 let element = array[i];
 if (element < 5) {
 results.push(element);
 count += 1;
   }
 }
Enter fullscreen mode Exit fullscreen mode

Here, we are looking for elements that are less than the number 5 in an array of numbers 0-9. We iterate through each element in the array, and push to the new results array when the condition is satisfied.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay