0

I have an array of people and want to filter on some criteria, in this case I want to search for a "male" which should return just one result however with this set I'm getting everything back because the regular expression is capturing female as well.

I tried matching on "\bmale" or "/\bmale" but didn't get anything back. I know I need to use a word boundary but for some reason it's not working out.

var people = [["Adelaide", 2, "yes", "female"],
           ["Ada", 2, "yes", "female"],
           ["Amanda", 1, "yes", "female"],
           ["Wolf", 3, "no", "male"],
           ["Rhonda", 1, "no", "female"]];

var isMale = function(x) {
  var myMatch = new RegExp("male");
  var test = String(x).match(myMatch);
  return String(x).match(myMatch);
}


var filteredArray=people.filter(isMale);

document.writeln(filteredArray); 
4
  • 3
    Just remind me one more time: Why are you using a Regex for this? Commented Sep 7, 2011 at 0:24
  • This could be done much more simply: var filteredArray = people.filter(function(itm) { return itm[2] == "male"; }); Commented Sep 7, 2011 at 0:27
  • @Joseph Silber - because it's convenient to filter a multidimensional array since that's what a match() returns. Unless there's an easier way? Commented Sep 7, 2011 at 0:30
  • @firedrawndagger - take a look at my answer, then come back here. Commented Sep 7, 2011 at 0:31

5 Answers 5

3

Don't use a regular expression when it's not necessary!!!

Use this instead:

var people = [
    ["Adelaide", 2, "yes", "female"],
    ["Ada", 2, "yes", "female"],
    ["Amanda", 1, "yes", "female"],
    ["Wolf", 3, "no", "male"],
    ["Rhonda", 1, "no", "female"]
];

var filteredArray = people.filter(function(el){
    return el[3] == 'male';
});

http://jsfiddle.net/XRHtZ/ (check your console)

Sign up to request clarification or add additional context in comments.

Comments

2

Why not just match against ^male, which would be the start of the line, immediately followed by "male"?

Comments

2

The word "female" contains the word "male" :-)

You filter should really just look at the simple value of the last element in the component sub-arrays. No need to use a regex; just compare:

return  x[3] === "male";

That's really all your "isMale()" function needs to do.

Comments

2

In my opinion, the beginning/end of string characters would be more appropriate here:

var myMatch = new RegExp('^male$');

1 Comment

And really, you could just do var myMatch = /^male$/; for brevity's sake.
1

If you want to only match items that are exactly "male", then just compare directly:

function isMale(x) {
    return(x == "male");
}

No need to use a regular expression for an exact match.

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.