5

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

1
  • 1
    May I ask you why you're trying to do in jQuery something that could be easily made with vanilla javascript? Commented Feb 21, 2014 at 20:49

3 Answers 3

10

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;
}); 
Sign up to request clarification or add additional context in comments.

3 Comments

Absolutely correct and the way to go. Use jQuery for manipulating the DOM, but javascript for manipulating variables.
well, there's $.grep - basically, an alias to filter, but works in iE8
@thg435 Yes, thanks for mentioning that. I had forgotten the $.grep() method.
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.

1 Comment

.indexOf is not applicable if you want to search for an exact word. For example if searchTerm = 'as' the above code will still work. What should be used if we want an exact match.
1

try this

var searchTerm = 'ensuite';
var itemsArray = ["2Bedroom Ensuite 2Bathroom", "1Bedroom Ensuite 1Bathroom", "3Bedroom 2Bathroom"];
for(var i=0;i<itemsArray.length;i++){
 var str=itemsArray[i];
  if(str.indexOf(searchTerm ) >= 0){
   //it contains searchterm do something with it.
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.