Guid
Guid

Reputation: 2216

Transform a string into an array of arrays in JavaScript

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.

Upvotes: 0

Views: 80

Answers (3)

igoratron
igoratron

Reputation: 134

If you are targeting an ES5 supporting browser you could use Array.map.

var array = "str1,str2,str3".split(",").map(function(token) {
     return [token]
});

Upvotes: 2

Peter Olson
Peter Olson

Reputation: 143037

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

Upvotes: 1

Tom Walters
Tom Walters

Reputation: 15616

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.

Upvotes: 2

Related Questions