Its ok if you have not worked with SQL or any database. I’ll explain what I mean. Let us assume, in JavaScript I have an array of values like ["Mourning Dove", "Bald Eagle", "Eurasian Collared-Dove"]. The array will look like this.
let arr = ["Mourning Dove", "Bald Eagle", "Eurasian Collared-Dove"];
I want to filter or search strings (or values) that have letters ov. See the first and last string has ov.
Sharing two simple methods here to do this.
1) Using filter() and includes() Method
In the first method I am using JavaScript array method filter() and includes().
<script> const arrBirds = ["Mourning Dove", "Bald Eagle", 'Eurasian Collared-Dove']; let filtered = arrBirds.filter(arrBirds => arrBirds.includes('ov')); document.getElementById("result").innerHTML = filtered; </script>
It’s a one line solution. You can use Regular Expressions (see the 2nd method below) to do this. However, I prefer using the filter() and includes() methods for this purpose. Since, it is more efficient and has some similarity with the SQL LIKE operator.
I have explained more about the filter() method here and why I recommend this method.
2) Using filter() with RegExp Object
You can also use Regular expression and get the same result. However, this method is slower than the method I have explained in the above example. I am using the RegExp object to match values with a pattern.
Note: You can learn more about RegExp object here.
The solution is simple though.
<script> const arrBirds = ["Mourning Dove", "Bald Eagle", 'Eurasian Collared-Dove']; let regex = new RegExp('ag', 'i'); // Create a regex object (a constructor). let filtered = arrBirds.filter(item => regex.test(item)); // Tests for a match. document.getElementById("result").innerHTML = filtered; </script>
The test() method of the RegExp object returns a true or false, when it finds a match between the specified string (in our case ag) and a regular expression.
Use the method that fits your requirement. Our objective is to filter or search for values in an Array using patterns in JavaScript.