Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Return all objects in an array that contain a text string

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

like image 917
william44isme Avatar asked Dec 19 '22 17:12

william44isme


2 Answers

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;
}); 
like image 182
undefined Avatar answered Mar 09 '23 00:03

undefined


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.

like image 44
aebabis Avatar answered Mar 08 '23 23:03

aebabis