Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search an array in Jquery like SQL LIKE %value% statement

I have an array with some values. How can I search that array using jquery for a value which is matched or close to it?

var a = ["foo","fool","cool","god"]; 

If I want to search for oo, then it should return foo, fool, and cool because these strings contain oo.

like image 550
KillerFish Avatar asked Mar 16 '11 11:03

KillerFish


People also ask

How do you search an array by value?

If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.) If you need to find if a value exists in an array, use Array.prototype.includes() .

Which method is used to search for a specific value in an array?

Using find() The find() method returns the first value in an array that matches the conditions of a function. If there is no match, the method returns undefined .

How do you check if an element is present in an array in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do I find an element in an array of arrays?

Use forEach() to find an element in an array The Array. prototype. forEach() method executes the same code for each element of an array. The code is simply a search of the index Rudolf (🦌) is in using indexOf.


2 Answers

Vanilla JS

To search in the array with Vanilla JS I would use the filter() method implemented into the Array prototype.

Note: For very large arrays you might want to consider refactoring those to async/await functions else it might slow down the user interface.

1. Using regular expressions (slower)

This is the most flexible approach as you could search for different patterns. You should be aware that the search term here is not a plain text, thus you have to escape most of non-alphanumeric chars according to the syntax. You should not pass unprocessed user input directly to the function, as it will not work as expected.

let a = ["foo","fool","cool","god"];  var term = 'oo'; // search term (regex pattern)  var search = new RegExp(term , 'i'); // prepare a regex object  let b = a.filter(item => search.test(item));  console.log(b); // ["foo","fool","cool"]

2. Using indexOf (faster)

In this particular case I would rather use indexOf() which is basically an equivalent of LIKE %term% but much faster than using regular expressions when working with large arrays.

It is a common case to do case-insensitive searches so make sure to use toLowerCase() for both the search terms and the array items. Otherwise remove it everywhere from the examples.

let a = ["foo","fool","cool","god"];  let term = 'oo';  let b = a.filter(item => item.toLowerCase().indexOf(term) > -1);  console.log(b); // ["foo","fool","cool"]

ES6 style (ES2015)

const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];    const filterItems = (needle, heystack) => {    let query = needle.toLowerCase();    return heystack.filter(item => item.toLowerCase().indexOf(query) >= 0);  }    console.log(filterItems('ap', fruits)); // ['apple', 'grapes']  console.log(filterItems('ang', fruits)); // ['mango', 'orange']

ES5 style

var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];    function filterItems(needle, heystack) {    var query = needle.toLowerCase();    return heystack.filter(function(item) {        return item.toLowerCase().indexOf(query) >= 0;    })  }    console.log(filterItems('ap', fruits)); // ['apple', 'grapes']  console.log(filterItems('ang', fruits)); // ['mango', 'orange']

This is the outdated answer

To search in the array with jQuery you might use jQuery.grep() or jQuery.map(). Both return new array with filtered elements using a callback function.

The fastest implementation (case insensitive) is using indexOf and toUpperCase in the callback:

var search_term = 'oo'; // your search term as string var search = search_term.toUpperCase(); var array = jQuery.grep(a, function(value) {     return value.toUpperCase().indexOf(search) >= 0; }); 

If you don't need case insensitive search you can remove both .toUpperCase() to speed it up even further.

More flexible but much slower (good enough for small arrays) is to use regular expression:

var search_term = "oo"; // search term var search = new RegExp(search_term , "i"); var arr = jQuery.grep(a, function (value) {     return search.test(value); }); 

or

var search_term = "oo"; // search term var search = new RegExp(search_term , "i"); var arr = jQuery.map(a, function (value) {     return value.match(search) ? value : null; }); 

Regular expressions allow you to make searches much more complex than %value%. However don't use it if you don't need it because it is many times slower.

you should get an array arr with the matched elements

like image 169
venimus Avatar answered Oct 14 '22 08:10

venimus


function find(arr) {     var result = [];      for (var i in arr) {         if (arr[i].match(/oo/)) {             result.push(arr[i]);         }     }      return result; }  window.onload = function() {     console.log(find(['foo', 'fool', 'cool', 'god'])); }; 

It prints ["foo", "fool", "cool"]

like image 21
Rendicahya Avatar answered Oct 14 '22 09:10

Rendicahya