4

Consider:

   var dummyArray =  [{
        "fname": "gali",
        "lname": "doe"
    }, {
        "fname": "john",
        "lname": "danny"
    }, {
        "fname": "joe",
        "lname": "dawns"
    }, {
        "fname": "liji",
        "lname": "hawk"
    }]

dummyArray = j$.grep(dummyArray, function(dt) {
             return (dt.fname== 'j');
});

How can I query the "fname" which contains letter "j" using the grep function?

1
  • use filter to find ALL, and find to find first, or some to check if it exist at all) they returns: array, one, bool respetively Commented Jan 21, 2022 at 17:18

4 Answers 4

5

Using the ECMAScript 5 standard function Array.filter to only return the elements matching the predicate:

Starting with "j"

var j = dummyArray.filter(function(o) {
    return o.fname.charAt(0) === 'j';
});

or, containing "j"

var j = dummyArray.filter(function(o) {
    return o.fname.indexOf('j') >= 0;
});
Sign up to request clarification or add additional context in comments.

Comments

4

You can use indexOf:

dummyArray = $.grep(dummyArray, function(dt) {
    return dt.fname.indexOf("j") != -1;
});

DEMO: http://jsfiddle.net/Nhmwk/

Comments

0

You can do this with vanilla JavaScript like so:

dummyArray = (function(){
  var result = [];
  for (var i=0, l=dummyArray.length; i<l; i++)
    if (/j/.test(dummyArray[i].fname))
      result.push(dummyArray[i]);
  return result;
}());

You can easily test stuff by changing the regex. For example, you could test for names that start by j instead of contain with /^j/.

Demo: http://jsfiddle.net/elclanrs/2Bw2y/

1 Comment

why accumulate your own array when we have $.grep and Array.filter ?
0

You can use the index of function:

dummyArray = $.grep(dummyArray, function(dt) {
    return dt.fname.indexOf("j") != -1;
});


// To be case-insensitive, use:
dummyArray = $.grep(dummyArray, function(dt) {
    return dt.fname.toLowerCase().indexOf("j") != -1;
});

Fiddle: http://jsfiddle.net/kYXPa/

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.