Posts tagged with arrays

regexInArray

September 8th, 2010

Javascript arrays have an inArray() method that tests for the existence of a search object and returns its key. However, sometimes you don’t want to test for an exact match. I wrote a little function that will test a regex instead. Like inArray() it returns -1 if none of the elements satisfy the condition.

function regexInArray(search, arr) {
  for (var k = 0; k < arr.length; k++) {
    if (search.test(arr[k])) {
      return k;
    }
  }
  return -1;
}

BFCollections

August 20th, 2010

I’ve been doing a bunch of PHP programming the last few weeks for a client and it’s been such a pain to use PHP’s archaic array_* methods. And don’t get me started on having to return arrays like array('result' => 'not_ok', 'message' => 'User not found') to indicate success or failure. I had some time to kill at the airport yesterday, so today I am happy to bring you BFCollections. The collections included are:

  • BFArray: A better array. It can be used just like a native array but it also has methods for common array operations such as map, filter, and reduceLeft.
  • Option: Indicates an optional return result, via the form of an instance of the Some class or the global $None. Inspired by Scala’s Option (naturally) and Haskell’s Maybe. There are basic methods to operate on the values.
  • Box: Again indicates an optional return result, though the lack of a value can also be indicated and even chained. Inspired by the Lift framework’s Box.

If there’s interest I’ll see about improving them and even adding additional collections.

A Subtle Javascript Mistake

January 29th, 2010

I was just pounding my head against what turned out to be a simple Javascript misconception that I hope I can save people from: in tests for the existance of a key, not a value, in an object or array. So the following work:

  var myObj = {1: "one", 2: "two"}
  1 in myObj // -> true
  2 in myObj // -> true
  var myArr = [1, 2]
  0 in myArr // -> true
  1 in myArr // -> true

But you might be surprised at the following results (I was):

  2 in myArr // -> false

That is because myArr has values 1 and 2 at keys 0 and 1, respectively. To test the existence of a value in an array, you need to use indexOf. For instance:

  myArr.indexOf(1) // -> 0
  myArr.indexOf(2) // -> 1
  myArr.indexOf("doesn't exist") // -> -1

As you can see, -1 indicates the value does not exist in the array.