JavaScript以垂直方式按索引排序数组

时间:2015-11-26 17:33:59

标签: javascript arrays sorting indexing

我有这个数组:[" A"," B"," C"," D"," E& #34;" F"" G"" H"" I"" J",& #34; K"" L"" M"" N"" O"" P&# 34;," Q"" R"" S"" T"" U"&# 34; V"" W"" X"" Y"" Z"]

我从服务器获取显示它的列数,对于这个例子,我选择了3。

到目前为止,我有这个功能可以正常工作,除非我的索引等于数组长度顺序出错,我不知道如何解决它。

var i;
var j;
var columns = window.columns; //3 for the example.
var lettersArray= ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var rows = Math.ceil(lettersArray.length/columns);

到目前为止,我有这个:

 for (i = 0; i < rows; i++)
            {
                     for (j=0; j < lettersArray.length; j=j+rows)  
                     {

                        var index = i+j;
                        if (index>=lettersArray.length)
                        {
                            break;
                        }
                        else
                        {
                          PrintArray(lettersArray, index); 
                        }   
                     }
            }

PrintArray函数在排序后接收索引和数组,它最终看起来像这样:

A J S 
B K T 
C L U 
D M V
E N W
F O X
G P Y 
H Q Z 
I R

但是出现问题的地方看起来像是:

A J S 
B K T 
C L U 
D M V
I N W
F O X
G P Y 
H Q R 
E Z

2 个答案:

答案 0 :(得分:2)

您所说的是想要通过row + col * rows遍历每个项目。您也不能停在 undefined 上,因为您可能还有更多的行。

这是一个如何做到这一点的例子,

function foo(data, cols) {
    var rows = Math.ceil(data.length / cols);
    var col, row;
    for (row = 0; row < rows; ++row)
        for (col = 0; col < cols; ++col)
            console.log(data[row + col * rows] || '');
}

console.log记录下一个项目或||空字符串。

答案 1 :(得分:0)

这是一个使用实际排序的解决方案。

var alphabet = [];
var i = 'A'.charCodeAt(0);
var j = 'Z'.charCodeAt(0);
for (; i <= j; i++)
  alphabet.push(String.fromCharCode(i));

function alphabetIndex(c) {
  return c.charCodeAt(0) - 'A'.charCodeAt(0);
}

var rowSize = 3; // AKA numCols; Retrieved from server.
var colSize = Math.ceil(alphabet.length / rowSize);
function sortKey(c) {
  return (rowSize * (alphabetIndex(c) % colSize)) +
         Math.floor(alphabetIndex(c) / colSize);
}

alphabet.sort(function(a, b) {
  return sortKey(a) - sortKey(b);
});

for (i = 0, j = alphabet.length; i < j; i += rowSize)
  console.log(alphabet.slice(i, i + rowSize).join(' '));