1

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?

var a = ["foo","fool","cool","god","acl"]; 

If I want to search for c, then it should return cool but not acl.

How I can achieve that?

2
  • How is c close to cool but not to acl ? Do you want the word to start with c ? Commented Aug 28, 2013 at 13:32
  • You can use regex as replacement for value% using /^value.*/ Commented Aug 28, 2013 at 13:39

5 Answers 5

2

Try this:-

arr = jQuery.grep(a, function (value) { search = /c/gi; if(value.match(search)) return true; return false; }); 

or

function find(arr) { var result = []; for (var i in arr) { if (arr[i].match(/c/)) { result.push(arr[i]); } } return result; } window.onload = function() { console.log(find(["foo","fool","cool","god","acl"])); }; 
Sign up to request clarification or add additional context in comments.

5 Comments

-1: jQuery? Where from?
@Jon: jQuery is right in the question title. And the question body. I've updated the tags.
Oh, right. Only looked at the tags, sorry.
Better return !!value.match(search)
@jcubic:- Yes I agree but I think OP can modify this as per his/her need. This answer will give him/her enough hint!!! ;)
1

Use substring to check if each string in the array begins with the string you are searching for:

var strings = [ "foo", "cool", "acl" ]; var needle = "c"; for (var i = 0; i < strings.length; ++i) { if (strings[i].substring(0, needle.length) === needle) { alert("found: " + strings[i]); } } 

Comments

1

A simple way to do it is to check for words starting with 'c' and iterate of the array.

var ar = ['acl','cool','cat'] for(var i = 0 ; i<ar.length ; i++){ console.log(ar[i].match(/^c/)) } //Prints: //null //["c", index: 0, input: "cool"] //["c", index: 0, input: "cat"] 

Comments

1

You can use the filter method which is available since JavaScript 1.6. It will give you back an array with the filtered values. Very handy if you want to match multiple items.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

var a = ["foo","fool","cool","god","acl"]; var startsWith = 'c'; a.filter(function (value) { return value && value.length > 0 && value[0] == startsWith; }); // yields: ["cool"] 

Comments

0
var a = ["foo","fool","cool","god","acl"]; var Character="f"; for(i=0;i<a.length;i++){ if(a[i].indexOf(Character)!=-1){ document.write(a[i]+"<br/>"); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.