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.
asked Mar 8, 2013 at 15:35
Guid
2,2262 gold badges23 silver badges34 bronze badges
3 Answers 3
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.
answered Mar 8, 2013 at 15:40
Tom Walters
15.6k7 gold badges59 silver badges75 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Guid
Argg, I'm screwed, I must support IE7. But thanks, it would be a fine solution for me.
Tom Walters
Gotta love IE keeping you on your toes! But that article details how to implement it yourself so all is not lost!
If you are targeting an ES5 supporting browser you could use Array.map.
var array = "str1,str2,str3".split(",").map(function(token) {
return [token]
});
Comments
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];
});
answered Mar 8, 2013 at 15:41
Peter Olson
144k49 gold badges210 silver badges250 bronze badges
1 Comment
Guid
Yes, it's more or less the solution I adopted (I'm using the Extjs "Ext.each()" method since I use this framework)
lang-js
["str1", "str2", str3"]?