I'm searching the shortest method to transform a string like
"str1,str2,str3,..."
into an array of arrays like :
[["str1"], ["str2"], ["str3"]]
I could use a loop or an each, but I wonder if there is something more elegant.
You can make use of split() and map() like so:
// This could be turned into 1 line but is split here for readibility
var array = string.split(',');
array = array.map(function(value){
return [value];
});
Note: map() doesn't exist in all implementations, check out this article for more info on it.
If you are targeting an ES5 supporting browser you could use Array.map.
var array = "str1,str2,str3".split(",").map(function(token) {
return [token]
});
Tom Walter's answer is great, but in case you don't want to use map:
var str = "str1,str2,str3";
var arr = str.split(",");
var arrOfarrs = [];
for(var i = 0; i < arr.length; i++) {
arrOfarrs.push([arr[i]]);
}
Alternatively, you can add a map polyfill to add support for older browsers:
Array.prototype.map = Array.prototype.map || function(fn) {
var arr = [];
for(var i = 0; i < this.length; i++) {
arr.push(fn(this[i]));
}
return arr;
};
which would then allow you to do
var arr = str.split(",").map(function(val) {
return [val];
});
["str1", "str2", str3"]?