Reputation: 18586
I have the following array...
var arr = [1,2,3,4,5,6,7,8,9]
I need to convert it to the following...
var newArr = [
[1,4,7],
[2,5,8],
[3,6,9],
];
Is this even possible?
Upvotes: 1
Views: 232
Reputation: 75317
Sure it's possible; something like this should work.
function manipulate(array, amount) {
// The array to return
var ret = [];
// Add the first few values to the array
// ret = [[1],[2],[3]];
for (var i=0;i<amount;i++) {
ret.push([array.shift()]);
}
// Now push the last few values on there.
for (var i=0;array.length;i = ++i % amount) {
ret[i].push(array.shift());
}
return ret;
}
and then call it like;
manipulate(arr, 3);
Upvotes: 4