miceana miceana - 6 months ago 14
Javascript Question

Pull values out of an array and into another array in a different order with JavaScript

I have an array like this:

var products = [

And need to pull the integers out of the array and format it like this:

var newProductsArray = [[1,3,5,7,9],[2,4,6,8,0]];

It needs to be able to be dynamic and expand because the
array will have more "columns".

I have this code but it's doing it backwards and can't figure out how to loop through and just break up the arrays. I am sure it's something simple I'm missing.

var metricStartPosition = 2;
var dataSetInnerArray = [];
var dataSetArray = [];

for (var i = 0; i < array.length; i++) {
for (var k = metricStartPosition; k < array[i].length; k++) {
dataSetInnerArray = [];


You can do something like this:

var products = [
var metricStartPosition = 2;
var newProductsArray = products.reduce(function(output, item) {
  item.slice(metricStartPosition).forEach(function(v, i) {
    (output[i] || (output[i] = [])).push(v);
  return output;
}, []);

Should work with any number of columns.

Of course you could use nested .forEach() loops or old-school nested for loops instead of .forEach() inside .reduce().