Array#partition – Useful JavaScript Game Extensions #20

Part 20 of 256

There comes a time in every programmer’s life when he must partition an array in twain. Separating apples from oranges, the wheat from the chaff, the yeas from the nays.

/**
 * Partitions the elements into two groups: those for which the iterator returns
 * true, and those for which it returns false.
 * @param {Function} iterator
 * @param {Object} [context] Optional context parameter to be
 * used as `this` when calling the iterator function.
 *
 * @type Array
 * @returns An array in the form of [trueCollection, falseCollection]
 */
Array.prototype.partition = function(iterator, context) {
  var trueCollection = [];
  var falseCollection = [];

  this.each(function(element) {
    if(iterator.call(context, element)) {
      trueCollection.push(element);
    } else {
      falseCollection.push(element);
    }
  });

  return [trueCollection, falseCollection];
};

Let’s see it in action:

// Separating apples from oranges (non-apples)
var result = ["apple", "apple", "orange", "apple", "orange", "orange", "orange", "apple"].partition(function(item) {
  return item == "apple";
});

// result is [["apple", "apple", "apple", "apple"], ["orange", "orange", "orange", "orange"]]

The result of using Array#partition is an array containing to elements, the first is the list of items that the iterator function evaluated to true for, and the second is the list that the iterator function evaluated to false for. You’d be surprised (probably not) how often dividing lists into two categories based on arbitrary criteria comes into play. Additionally this can be used as the foundation for simpler generic methods like select and reject. I’m sure they’ll turn up pretty soon.

Author: Daniel X

Heretic priest of the Machine God. I enjoy crawling around in Jeff Bezo's spaceship, bringing technology to the people, and long walks outside of time and space.

One thought on “Array#partition – Useful JavaScript Game Extensions #20”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: