2D阵列到3D阵列Javascript(Google Script)

时间:2018-01-27 18:15:16

标签: javascript arrays google-apps-script

如果我有一个数组:

var arr = [ 
            [1,2,3,4,5,6,7,8,9] , 
            [11,12,13,14,15,16,17,18,19] 
          ];

我怎样才能转换为

var newArr = [ 
               [ [1],[2],[3],[4],[5],[6],[7],[8],[9]          ] , 
               [ [11],[12],[13],[14],[15],[16],[17],[18],[19] ] 
             ]

我尝试从while(arr.length) newArr.push(arr.splice(0,1));开始,但我无处可去。

5 个答案:

答案 0 :(得分:1)

您可以简单地将旧数组映射到新数组。

var newArray = arr.map( second => second.map( third => [ third ] ))

或更向后兼容的版本

var newArray = []
for(var i = array.length - 1; i >= 0; i—-){
    var second = array[i];
    newArray[i] = []
    for(var j = second.length - 1; j >= 0; j—-){
        newArray[i][j] = [ second[j] ]
    }
}

答案 1 :(得分:0)

我不知道Google Apps脚本是否有Array#map,但如果是这样,这是它的经典用例:您希望将地图中的所有条目转换为新条目:

var arr = [ 
  [1,2,3,4,5,6,7,8,9] , 
  [11,12,13,14,15,16,17,18,19] 
];
arr = arr.map(function(sub) {
  return sub.map(function(entry) {
    return [entry];
  });
});
console.log(arr);
.as-console-wrapper {
  max-height: 100% !important;
}

如果没有,或者你不喜欢所有这些回调,嵌套的for循环会这样做:

var arr = [ 
  [1,2,3,4,5,6,7,8,9] , 
  [11,12,13,14,15,16,17,18,19] 
];
for (var i = 0; i < arr.length; ++i) {
  var sub = arr[i];
  for (var j = 0; j < sub.length; ++j) {
    sub[j] = [sub[j]];
  }
}
console.log(arr);
.as-console-wrapper {
  max-height: 100% !important;
}

答案 2 :(得分:0)

递归解决方案:

&#13;
&#13;
var arrayify = function(input) {
    var ret = [];
    if(Array.isArray(input)) {
        input.forEach(function(element) {
            ret.push(arrayify(element));
        });
    } else {
        ret.push(input);
    }
    return ret;
};

var arr = [ 
    [1,2,3,4,5,6,7,8,9], 
    [11,12,13,14,15,16,17,18,19] 
];

var newArray = arrayify(arr);
console.log(newArray);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

没有ES6的简单解决方案可能是:

var arr = [ 
            [1,2,3,4,5,6,7,8,9] , 
            [11,12,13,14,15,16,17,18,19] 
          ];
var newArr = [];
arr.forEach(function(data,index){
    newArr[index] = [];
   data.forEach(function(d){
    var temp = [];
    temp.push(d);
    newArr[index].push(temp);
   });

})

console.log(newArr);

答案 4 :(得分:0)

多样化的低效替代品:

arr = [ [1,2,3,4,5,6,7,8,9], [11,12,13,14,15,16,17,18,19] ]

newArr = JSON.parse( JSON.stringify(arr).replace(/[^[,\]]+/g, '[$&]') )

console.log( newArr )