Skip to content

Instantly share code, notes, and snippets.

@tmcw
Last active December 13, 2015 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmcw/4967929 to your computer and use it in GitHub Desktop.
Save tmcw/4967929 to your computer and use it in GitHub Desktop.
Array Pretty Print

Pretty print nested arrays

// Instead of
[Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3], Array[3]]

// or
[ [ 0, 0, 0 ],
  [ 0.5, 0.5, 0.5 ],
  [ 4.667, 2.5, 2.5 ],
  [ 10, 5.167, 3 ],
  [ 22.8, 9.333, 7.167 ],
  [ 45.333, 18, 11.333 ],
  [ 69.714, 24.75, 14 ],
  [ 255.5, 119.333, 74.75 ] ]
  
// get this:

arrayPrettyPrint(x); // yields:

[
  [     0.000,      0.000,      0.000],
  [     0.500,      0.500,      0.500],
  [     4.667,      2.500,      2.500],
  [    10.000,      5.167,      3.000],
  [    22.800,      9.333,      7.167],
  [    45.333,     18.000,     11.333],
  [    69.714,     24.750,     14.000],
  [   255.500,    119.333,     74.750]
]
function arrayPrettyPrint(a) {
var s = '[\n';
for (var i = 0; i < a.length; i++) {
s += ' [' + a[i].map(function(x) {
var n = x.toFixed(3)
while (n.length < 10) {
n = ' ' + n;
}
return n;
}).join(', ') + ']';
if (i !== a.length - 1) s += ',';
s += '\n';
}
s += ']';
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment