0

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.

3
  • Do you definately each of those string in an array inside an array that has nothing else in it or did you really mean ["str1", "str2", str3"]? Commented Mar 8, 2013 at 15:40
  • I really need to get an array of arrays. Commented Mar 8, 2013 at 15:50
  • fair enough, just checking it wasn't a misunderstanding of syntax that would yeald answers you didn't want. Commented Mar 8, 2013 at 15:51

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Argg, I'm screwed, I must support IE7. But thanks, it would be a fine solution for me.
Gotta love IE keeping you on your toes! But that article details how to implement it yourself so all is not lost!
2

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

1

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];
});

1 Comment

Yes, it's more or less the solution I adopted (I'm using the Extjs "Ext.each()" method since I use this framework)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.