Prototype Enumerable partition() Method


Advertisements


This method partitions the elements in two groups:

  • Those regarded as true.
  • Those considered false.

By default, regular JavaScript boolean equivalence is used, but an iterator can be provided, that computes a boolean representation of the elements.

This is a preferred solution to using both findAll/select and reject: it only loops through the elements once!

The optional context parameter is what the iterator function will be bound to. If used, the this keyword inside the iterator will point to the object given by the argument.

Syntax

Iterator.partition([context]);

Return Value

  • Returns an array in the form [[Array of the true values], [Array of the false values]].

Example

<html>
<head>
<title>Prototype examples</title>
<script type="text/javascript" 
   src="/javascript/prototype.js">
</script>

<script>

function showResult(){

  var arr = ['hello', null, 42, false, true, , 17].partition();

  alert("Test 1 : " + arr.inspect() );
  // Returns [['hello', 42, true, 17], [null, false, undefined]]

  var arr = $R(1, 10).partition(function(n) {
  return 0 == n % 2;
  })

  alert("Test 2 : " + arr.inspect() );
  // Returns   [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
}

</script>
</head>

<body>

  <p>Click the button to see the result.</p>
  <br />
  <br />
  <input type="button" value="Result" onclick="showResult();"/>

</body>
</html>

To understand it in better way you can Try it yourself.


prototype_enumerating.htm

Advertisements