WEBDOOD.COM

Archive for September, 2010

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 :, , more...

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