Skip to content

Instantly share code, notes, and snippets.

@jhsuZerion
Created August 25, 2017 17:57
Show Gist options
  • Save jhsuZerion/0330ee30fbe74f4830d08477ff2b1000 to your computer and use it in GitHub Desktop.
Save jhsuZerion/0330ee30fbe74f4830d08477ff2b1000 to your computer and use it in GitHub Desktop.
Convert a subform to a multi-dimensional array specified by the second parameter
/**
* function returns subform as 2D array
* @param {object} r valid JSON object
* @param {int} n integer greater than 1
* @return {object} 2D array where number of objects per row is equal to n
*/
function subform_to_multi_array(r,n) {
if(typeof n !== 'number' || n !== Math.floor(n) || n <= 1 || n > r.length) return r;
var cols = [];
var count = 0;
var row = 0;
for(var i=0; i<r.length; i+=n) {
cols[row] = [];
for(var j=0; j<n; j++) {
if(count < r.length) {
cols[row].push(r[count]);
count++;
}
}
row++;
}
return cols;
}
@jhsuZerion
Copy link
Author

jhsuZerion commented Nov 7, 2017

Different version used for columns:

/**
 * function returns subform as 2D array
 * @param  {object}  r  valid JSON object
 * @param  {int}     n  integer greater than 1
 * @return {object}     2D array where number of objects per row is equal to n
 */
function subform_to_multi_array(r, n) {
   if (typeof n !== 'number' || n !== Math.floor(n) || n <= 1 || n > r.length) return r;
   var cols = [];
   var count = 0;
   var num = 0;

   for (var i = 0; i < r.length; i++) {
      num = String(i%n);
      if (i !== 0 && num === "0") { count++; }
      if(num === "0") { cols[count] = {}; }
      
      cols[count][num] = r[i];
      
   }

   return cols;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment