Thursday, September 29, 2011

JavaScript helpers: Iterating an array while skipping select elements

 
Array.prototype.iterate || (Array.prototype.iterate = function (callback, ignore) {
  var i = 0, j = this.length;
    for (; i < j; ++i) {
        if (ignore && ignore(this[i], i)) {
          continue;
        } 
        
        callback(this[i], i);
    }
});

Usage

Here's how we can use it to iterate over a couple of numbers, skipping over the even ones:
 
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

arr.iterate(function (el) {
  console.log(el);
}, function (el) {
  return !(el % 2);
});

Output:
1
3
5
7
9

Here's another example, this time involving objects:
 
var queen = function (reference) {
    return {
        ref: reference
    };
}, arr = [queen("Aragon"), queen("Boleyn"), queen("Seymour"), queen("Cleves"), queen("Howard"), queen("Parr")];

arr.iterate(function (el, i) {
  console.log(i, el.ref);  
}, function (q) {
  return q.ref === "Boleyn"  || q.ref === "Howard";
});
Output (the queens who died with their heads on):
0 Aragon
2 Seymour
3 Cleves
5 Parr

If no ignore function is passed as the second parameter of the iterate method, no elements are skipped:
 
var arr = ["Mr. Albert Show", "Fusion Orchestra", "Fuzzy Duck", "Minotaurus"];

arr.iterate(function (el, i) {
  console.log(el);  
});
Output
Mr. Albert Show
Fusion Orchestra
Fuzzy Duck
Minotaurus