If I have an array:
var arr = [
[1,2,3,4,5,6,7,8,9] ,
[11,12,13,14,15,16,17,18,19]
];
How could I convert to
var newArr = [
[ [1],[2],[3],[4],[5],[6],[7],[8],[9] ] ,
[ [11],[12],[13],[14],[15],[16],[17],[18],[19] ]
]
I tried start from something like while(arr.length) newArr.push(arr.splice(0,1)); but I am getting nowhere.
5 Answers 5
I don't know if Google Apps Script has Array#map, but if so, this is the classic use case for it: You want to transform all of the entries in the map into new entries:
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;
}
If not, or if you don't like all those callbacks, nested for loops would do it:
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;
}
Comments
You can simply map old array to the new one.
var newArray = arr.map( second => second.map( third => [ third ] ))
Or more backwards compatible version
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] ]
}
}
2 Comments
Array#map.A simple solution without ES6 could be:
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);
1 Comment
Array#map. If you're creating an array, then looping through another and pushing entries in the one you just created, you want map.Recursive solution:
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);
Comments
Inefficient alternative for variety:
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 )
Comments
Explore related questions
See similar questions with these tags.