jPaq Example - Flatten Arrays

One of the nice functions that is provided in Prototype is Array.prototype.flatten().  It gives you the ability to turn arrays such as [0, [1, [2, [[[3]]]]], 4] into [0, 1, 2, 3, 4] by just calling the flatten function. This may seem like a challenging process to duplicate, but fortunately it isn't as long as you can curry functions and reduce arrays; both of which can be done in any browser with jPaq.  The following shows how you can define the same flatten() function in just three lines of code:

The question is, does that code really work?  You can try it out yourself with the executable examples below:

In the example arrOld is an which contains a number, an array, and another number.  In total there are five numbers in arrOld, but you must drill down into the array in order to reveal all of the numbers.  arrNew is defined as the flattened version of arrOld.  This new array contains five numbers and no arrays.  The aforementioned facts are verified by the results shown by executing the above code.  If you are running a newer browser like Chrome, Firefox, or IE9, you will be able to even see a representation of the arrays.

In the end, the fact that Array.prototype.reduce() is natively defined in newer browsers, definitely proves advantageous, as is shown by this example.  Still, as I mentioned at the onset, this example would not be possible without Function.prototype.curry().  Perhaps this new function will become natively available in newer browsers.  Even if that happens, though, web developers will still benefit from using jPaq, because these functions can be used in older and newer browsers.

Applicable Parts

Related Examples

  1. Currying
    At times, you may want to call a function a number of times, but you may notice that the first few arguments are always the…
  2. Reducing to the Longest Word
    Enter as many words as you want in the textbox below and then press the "Get Longest Word Length" button to see how many characters…
  3. Currying Up String Functions
    You ever wonder how libraries such as jPaq and Prototype add prototype functions to different classes?  At for jPaq, it isn't by relying…
  4. Cartesian Product
    A few weeks ago, I came across a question about finding the cartesian product of two or more arrays in JavaScript.  The following is…
  5. Compacting Arrays
    The JavaScript library Prototype offers a function which basically removes all of the undefined and null values from the array. Fortunately, JavaScript 1.6 offers…