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?

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
bhawin
  • 267
  • 1
  • 6
  • 15

5 Answers5

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"]));
};
Bart
  • 17,070
  • 5
  • 61
  • 80
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
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]);
    }
}
Jon
  • 428,835
  • 81
  • 738
  • 806
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"]
raam86
  • 6,785
  • 2
  • 31
  • 46
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"]
Bart
  • 17,070
  • 5
  • 61
  • 80
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/>");
    }
 }
Rejayi CS
  • 1,034
  • 1
  • 10
  • 22