Searching array of objects using jquery grep with wildcards
15,369
You can use String.indexOf() here, =
will not work with wild chars
var resultSet = $.grep(courses, function (e) {
return e.code.indexOf('ENCH3TH') == 0;
});
Demo: Fiddle
Or use regex
var regex = /^ENCH3TH/
var resultSet = $.grep(courses, function (e) {
return regex.test(e.code);
});
Demo: Fiddle
Author by
Randhir Rawatlal
Updated on June 06, 2022Comments
-
Randhir Rawatlal almost 2 years
I'm searching an array of objects using jquery grep and would like to include wildcards in the search. For example, I have an array as follows:
courses = [ {code: 'ENCH3TH', otherFields: otherStuff}, {code: 'ENCH3THHS1', otherFields: otherStuff}, {code: 'ENCH3TH2', otherFields: otherStuff}, {code: 'ENCH4RT', otherFields: otherStuff}, {code: 'ENCH4MT', otherFields: otherStuff}]
I'd like to get all the courses with the ENCH3TH prefix. I have attempted
var resultSet = $.grep(courses, function(e){ return e.code == 'ENCH3TH/'; });
..to no avail (note the use of the '/' after 'ENCH3TH' as the wildcard).