-1

I just came up with an inArray implementation for javascript and it's working fine. Its weird but short, and i've got this feeling that there's something wrong with it, but i'm not sure what it is:

Array.prototype.inArray = function (itm) {
  return this.join("|").match( new RegExp('\\b'+itm+'\\b','ig')  );
}

UPDATE: this is supposed to be a general implementation of an inArray feature. I'm not sure which is more expensive, doing a loop or creating a regex

7
  • What are the requirements of your implementation? To what standard should we compare it? How can we know if something is "wrong" unless you define what "right" would be? Commented Oct 17, 2012 at 20:57
  • 1
    You have to escape every element and the search term for special regex characters. Just imagine if an element contains | or * or .. So if you are going to iterate over all elements anyway, you can directly compare them. Commented Oct 17, 2012 at 20:59
  • It only work on strings? Commented Oct 17, 2012 at 21:00
  • 3
    Watch out for string elements containing pipes. Look at this question: stackoverflow.com/questions/890782/javascript-function-inarray Commented Oct 17, 2012 at 21:01
  • 2
    Doing a RegExp is going to be flawed on so many levels. Better to just use a loop and test for equality. Commented Oct 17, 2012 at 21:05

2 Answers 2

0

I don't know what your implementation requirements are, but keep these in mind:

  • you'll be matching a stringified version of the Array members, not the actual members

  • the \\b will allow any word break, including punctuation, giving false positives.

  • it would only be useful for single word entries in the Array, otherwise you could get false positives

  • you'll be returning null or and Array of "matches". Not sure if that's what you'd want.

I'm sure these just scratch the surface.

If you are implementing a very narrow functionality, it could work, but would be not be adequate for general use.

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

1 Comment

currently i'm just using it to check for serialno type of data, but i'm quite sure this is going to be expensive given a large sample.
0

Use underscore.js intersection() method to find out if your array contain an element or even a series of elements:

if(_.intersection(yourArray, [item]).length){
    //do stuff
}

you can check for multiple items by pushing them into an array too. It also covers any type of object

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.