-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

hakre
  • 193,403
  • 52
  • 435
  • 836
brianff
  • 175
  • 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? – I Hate Lazy Oct 17 '12 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. – Felix Kling Oct 17 '12 at 20:59
  • It only work on strings? – gosukiwi Oct 17 '12 at 21:00
  • 3
    Watch out for string elements containing pipes. Look at this question: http://stackoverflow.com/questions/890782/javascript-function-inarray – Denys Kniazhev-Support Ukraine Oct 17 '12 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. – JasonWyatt Oct 17 '12 at 21:05
  • Your code has to convert every array element to a string, which in general can be an unknown amount of work, and may for some object types produce nonsense results. – Pointy Oct 17 '12 at 21:06
  • Have you ever heard of `Array.indexOf`? –  Sep 09 '13 at 13:35

2 Answers2

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.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • 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. – brianff Oct 17 '12 at 21:13
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

Mohsen
  • 64,437
  • 34
  • 159
  • 186