组织Javascript数组

时间:2014-04-04 13:52:48

标签: javascript arrays csv

我从函数中检索数据并将其存储在以下列方式构造的Javascript数组中。

当我打印我的阵列时,我得到了下面的

day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-07,2,0,0,0,0,1,0,0,
2014-03-22,0,0,0,0,0,0,0,0,
2014-03-09,0,0,0,0,0,0,0,0,
2014-03-12,1,0,0,0,0,1,0,0,
2014-03-25,1,0,0,0,0,0,0,0,
2014-03-26,1,0,0,0,0,0,0,0,
2014-03-08,1,0,0,0,0,1,0,0,
2014-03-16,1,0,0,0,0,0,0,0,
2014-03-19,0,0,0,0,0,0,0,0,
2014-03-23,0,0,0,0,0,0,0,0,
2014-03-13,1,0,0,0,0,1,0,0,
2014-03-10,1,0,0,0,0,2,0,0,
2014-03-14,0,0,0,0,0,0,0,0,
2014-03-31,2,0,0,0,0,1,0,0,
2014-04-02,0,0,0,0,0,0,0,0,
2014-03-11,0,0,0,0,0,0,0,0,
2014-03-30,4,0,0,0,0,2,0,0,
2014-03-21,1,0,0,0,0,0,0,0,
2014-03-06,0,0,0,0,0,0,0,0,
2014-03-05,1,0,0,0,0,0,0,0,
2014-03-27,6,0,0,0,0,2,0,0,
2014-03-15,2,0,0,0,0,2,0,0,
2014-03-17,0,0,0,0,0,0,0,0,
2014-03-24,1,0,0,0,0,0,0,0,
2014-03-28,17,0,0,0,0,9,0,0,
2014-04-01,1,0,0,0,0,0,0,0,
2014-03-29,3,0,0,0,0,1,0,0,
2014-03-18,0,0,0,0,0,0,0,0,
2014-03-20,1,0,0,0,0,1,0,0

我想修改上面的数组,使其以下列方式显示,然后将内容存储在csv文件中

day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-07,2,0,0,0,0,1,0,0,
day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-22,0,0,0,0,0,0,0,0,
day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-09,0,0,0,0,0,0,0,0,
day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-12,1,0,0,0,0,1,0,0,
day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-25,1,0,0,0,0,0,0,0,
day,views,likes,shares,comments,dislikes,estimatedMinutesWatched,favoritesAdded,favoritesRemoved,
2014-03-26,1,0,0,0,0,0,0,0,

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

如果我有理解,你有一个一维数组,你想要一个矩阵?

这里有9个标签吗?所以你可以使用:

function arrayToMatrix(array, colums) {
    var matrix = [], size = array.length;    
    for (i = 0, k = -1; i < size; i++) {
        if (i % colums=== 0) {
            k++;
            matrix[k] = [];
        }    
        matrix[k].push(array[i]);
    }    
    return matrix;
}

所以使用:

var matrix = arrayToMatrix(array,9);

然后你必须用CSV打印它。

function matrixToCSV(matrix){
     var result = '';
     for (var i = 0; i < matrix.length; i++){
          for (var j = 0; i < matrix[i].length; j++){ //print each line
              if (j == 0 ){
                   result += matrix[i][j];
              }else{
                   result += ',' + matrix[i][j];
              }              
          }
          result += ';\n'; //new line
     }
     return result;
}

然后:

var CSVFile = matrixToCSV(matrix);

注意:在CSV中,您不需要重复标签。