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.

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

  1. Pingback: Select and Reject – Useful JavaScript Game Extensions #22 and #23

Leave a Reply

Your email address will not be published. Required fields are marked *