Suppose this is my input: "0.1412898495873448 -0.03307049805768848 -0.0002348551519150674 0.0007142371877833145 -0.01250041632738383 0.4052674201000387 -0.02541421100956797 -0.02842612870208528 1803.701163338969 1796.443677744862 1986.31441429052 1442.354524622483"
Sylvester has this constructor. It requires a nested array.
It's simple enough to make the string into an array of numbers using String.split()
and map
and friends.
Something not unlike this:
var nums = line.split(/ |\n/);
nums.map(function(num) {return parseFloat(num);});
But I think Javascript is missing a functional-style function that can "group" my 16-array into 4 rows of 4 numbers.
I thought maybe a JS utility library such as underscore might have me covered.
Doesn't look like it.
What's the most elegant and/or efficient way to do this? Do I have to use a for loop?
function nest(array, range) {
var l = array.length;
var ret = [];
var cur = null;
for (var i=0; i<l; ++i) {
if (!(i%range)) {
cur = [];
ret.push(cur);
}
cur.push(array[i]);
}
return ret;
}
Node tells me this works:
> function nest(array, range) {
... var l = array.length;
... var ret = [];
... var cur = null;
... for (var i=0; i<l; ++i) {
..... if (!(i%range)) {
....... cur = [];
....... ret.push(cur);
....... }
..... cur.push(array[i]);
..... }
... return ret;
... }
undefined
> nest([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],4)
[ [ 0, 1, 2, 3 ],
[ 4, 5, 6, 7 ],
[ 8, 9, 10, 11 ],
[ 12, 13, 14, 15 ] ]
>
Can anyone think of a better way to do it?