如何在 Jquery 中搜索数组,如 SQL LIKE %value% 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5324798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to search an array in Jquery like SQL LIKE %value% statement
提问by KillerFish
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?
我有一个包含一些值的数组。如何使用 jquery 在该数组中搜索与其匹配或接近的值?
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
.
如果我想搜索oo
,那么它应该返回foo
, fool
, 并且cool
因为这些字符串包含oo
.
回答by venimus
Vanilla JS
香草JS
To search in the array with Vanilla JS I would use the filter()
method implemented into the Array prototype.
要使用 Vanilla JS 在数组中搜索,我将使用filter()
在 Array 原型中实现的方法。
Note: For verylarge arrays you might want to consider refactoring those to async/awaitfunctions else it might slow down the user interface.
注意:对于非常大的数组,您可能需要考虑将它们重构为async/await函数,否则它可能会降低用户界面的速度。
1. Using regular expressions (slower)
1. 使用正则表达式(较慢)
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)
2.使用indexOf
(更快)
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.
在这种特殊情况下indexOf()
,LIKE %term%
在处理大型数组时,我宁愿使用它基本上相当于但比使用正则表达式快得多。
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.
进行不区分大小写的搜索是一种常见情况,因此请确保toLowerCase()
同时用于搜索词和数组项。否则,将其从示例中的任何地方删除。
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)
ES6 风格 (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
ES5风格
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()
orjQuery.map()
. Both return new array with filtered elements using a callback function.The fastest implementation (case insensitive) is using
indexOf
andtoUpperCase
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
这是过时的答案
要使用 jQuery 在数组中搜索,您可以使用
jQuery.grep()
或jQuery.map()
。两者都使用回调函数返回带有过滤元素的新数组。最快的实现(不区分大小写)是在回调中使用
indexOf
和toUpperCase
: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; });
如果您不需要不区分大小写的搜索,您可以删除两者
.toUpperCase()
以进一步加快搜索速度。更灵活但更慢(对于小数组足够好)是使用正则表达式:
var search_term = "oo"; // search term var search = new RegExp(search_term , "i"); var arr = jQuery.grep(a, function (value) { return search.test(value); });
或者
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; });
正则表达式允许您使搜索比
%value%
. 但是,如果您不需要它,请不要使用它,因为它会慢很多倍。你应该得到一个
arr
包含匹配元素的数组
回答by Rendicahya
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"]
它打印 ["foo", "fool", "cool"]
回答by Clyde Lobo
Try the following js code
试试下面的js代码
function likeMatch(q)
{
my_arr = ["foo","fool","cool","god"];
var rArr=[];
for(var t in my_arr)
{
if(my_arr[t].indexOf(q)>0)
rArr.push(my_arr[t]);
}
return(rArr);
}
回答by user2311489
try this:
尝试这个:
var infoData = ["foo","fool","cool","god"],
search = 'oo';
//this makes the magic
infoData = $$(infoData).filter(function(){
return (this.search(search) >= 0)
})
var n = infoData.length;
console.log("size result: "+ n );
for(var item = 0; item < n ;item++){
console.log("item: "+item+" data : "+infoData[item]);
}
result:
结果:
size result: 3
item: 0 data : foo
item: 1 data : fool
item: 2 data : cool
回答by agershun
You can do it with AlasqlJavaScript SQL library. It supports LIKE operator, like in SQL
您可以使用AlasqlJavaScript SQL 库来实现。它支持 LIKE 运算符,就像在 SQL 中一样
var a = ["foo","fool","cool","god"];
var searchString = "%oo%";
var res = alasql('SELECT COLUMN * FROM [?] WHERE [0] LIKE ?',[a, searchString]);
Try this exampleat jfFiddle.
在 jfFiddle试试这个例子。
回答by Apoorv
use the following function if you are searching in array containing hashes object
如果您在包含哈希对象的数组中搜索,请使用以下函数
function searchInArrayofHashes(array,key,keyword) {
responsearr = []
for(i=0;i<array.length;i++) {
if(array[i][key].indexOf(keyword) > -1 ) {
responsearr.push(array[i])
}
}
return responsearr
}
回答by Alistair Laing
try $.inArray
http://api.jquery.com/jQuery.inArray/. I'm not sure if it will allow you to use a regular expression but its worth a try
尝试$.inArray
http://api.jquery.com/jQuery.inArray/。我不确定它是否允许您使用正则表达式,但值得一试