DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Arrange //JavaScript Function

09.09.2005
| 6715 views |
  • submit to reddit
        <a href="http://www.jsfromhell.com/array/arrange">
It arranges elements in an array, the "n" parameter determines the amount of elements in each combination and the "m" one is a boolean which says if the function should return an array with an "index map" or real values.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/arrange [v1.0]

arrange = function( v, n, m ){
 	for( var i, j, k, sep = sep || "", l = v.length, r = new Array( i = Math.pow( l, n ) ), c = ( new Array( n + 1 ) ).join( 0 ).split( "" ); i; )
		for( r[--i] = new Array( j = n ), k = 1; j--; r[i][j] = m ? c[j] : v[c[j]], k && ( ++c[j] != l && --k, c[j] %= l ) );
	return r;
};


Example

document.write( arrange( ["A", "B", "C" ], 3, 1 ).join( "<br />" ), "<hr />" );
document.write( arrange( ["A", "B", "C" ], 3, 0 ).join( "<br />" ) );