Is it possible to search an array for a string of text, then return the contents of the objects which contain it?
For example:
<script>
var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
var searchTerm = 'ensuite';
var results = $.searchThing('itemsArray', searchTerm);
document.write(results);
</script>
The above hypothetical script (where 'searchThing' is the method - if it exists) should write
2Bedroom Ensuite 2Bathroom
2Bedroom Ensuite 2Bathroom
Does this exist? How can it be done?
Thanks
You can use the ES5 Array.prototype.filter
method:
var results = itemsArray.filter(function (elem) {
return elem.toLowerCase().indexOf(searchTerm) > -1;
});
Note that older browsers don't support the .filter()
method. For supporting those browsers you can use a polyfill.
edit: You can also use the jQuery $.grep()
utility function:
var results = $.grep(itemsArray, function(elem) {
return elem.toLowerCase().indexOf(searchTerm) > -1;
});
This is possible to do in jQuery (sort of), but it isn't necessary to use jQuery. Here's a jQuery solution anyway
var itemsArray = ['asdf','1234'];
var searchTerm = 'asdf';
var results=[];
$.each(itemsArray, function(i,e){
if(e.indexOf('asdf') > -1)
results.push(e);
});
I would prefer undefined's solution personally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With