WEBDOOD.COM

Javascript: Flatten an array containing arrays

by webdood on Sep.08, 2010, under Javascript, Software Development

This quick function takes a an array, whose elements may or may not be other arrays, and flattens it into a single array.

Extremely simple solution, but kind of fun because it’s a chance to use recursion:

<script type=text/javascript>
var a = [1,2,[5,6,7], 8, [9,10,[11,12],13], 14];

function flatten( oArray ) {
  var retVal = [];
  for (var i=0;i<oArray.length;i++) {
    if (!isArray( oArray[i]) ) {
      retVal.push( oArray[i] );
    } else {
      var tempFlatt = flatten(oArray[i]);
      for (var j=0;<tempFlatt.length;j++) {
        retVal.push( tempFlatt[j] );
      }
    }
  }
  return retVal;
}

function isArray( anElement ) {
  return (typeof anElement=="object" && anElement.constructor == Array);
}

alert(flatten(a));
</script>
:, ,

2 Comments for this entry

  • WoodrowShigeru

    You have a significant typo in this, as the tempFlatt-for-loop is missing a j in the header.

    Otherwise, it works.

  • Christopher Hall

    Here is a modern version of this snippet, complete with Array.isArray

    var flatten = function (array) {
    “use strict”;
    var returnValue = [];
    var temporaryFlatArray;
    for (var i = 0; i < array.length; i++) {
    if (!Array.isArray(array[i])) {
    returnValue.push(array[i]);
    } else {
    temporaryFlatArray = flatten(array[i]);
    for (var j = 0; j < temporaryFlatArray.length; j++) {
    returnValue.push(temporaryFlatArray[j]);
    }
    }
    }
    return returnValue;
    };

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org