DEV Community

stuxnat
stuxnat

Posted on

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.

Top comments (0)