Pregunta

I am trying to convert an vertical array list, into a horizontal one, I don't really need to resort the original list, but are really looking for a formula that considers, the rows, cols and array size as variables in the function.

The best way of explaining this is to show the original array and how the data is outputted in columns, and the sorted array which is outputted in rows.

For other reasons, I cannot just output my data in rows, I still have to output it in columns, only sorted into rows.

[1,2,3,4,5,6,7,8,9,10,11,12]

1   5   9
2   6   10
3   7   11
4   8   12

[1,4,7,10,2,5,8,11,3,6,9,12]

1   2   3
4   5   6
7   8   9
10  11  12

What I would like to do is to loop through the original array, apply a formula and select the correct index from the original array based on the formula, trouble is I just can't figure out what the some_formula should be.

var cols = 3;
var rows = arr.length / cols;
var arr=[1,2,3,4,5,6,7,8,9,10,11,12];
for (i=0;i<arr.length;i++){
    var cell = arr[i] * ##some_formula, cols, rows##
}
¿Fue útil?

Solución

Something like this should work:

var cell = arr[ (i * columns + Math.floor(i/rows)) % arr.length ];

In your case, columns should be 3 and rows should be 4

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top