In JavaScript, is it possible to split each string in a multidimensional array of strings using a separator? I'm trying to split a multidimensional array of strings using a string separator, but I don't yet know how to iterate over a multidimensional array without using multiple for-loops.
var theArray = [["Split,each"],["string, in"],["this, array"]];
As far as I know, it isn't possible to apply the string.split(",")
method to a multidimensional array. I'll need to find a workaround, since this code isn't valid:
alert([["Split,each"],["string, in"],["this","array"]].split(","));
In JavaScript, is it possible to split each string in a multidimensional array of strings using a separator? I'm trying to split a multidimensional array of strings using a string separator, but I don't yet know how to iterate over a multidimensional array without using multiple for-loops.
var theArray = [["Split,each"],["string, in"],["this, array"]];
As far as I know, it isn't possible to apply the string.split(",")
method to a multidimensional array. I'll need to find a workaround, since this code isn't valid:
alert([["Split,each"],["string, in"],["this","array"]].split(","));
Share
Improve this question
edited May 12, 2013 at 3:58
Anderson Green
asked May 12, 2013 at 3:15
Anderson GreenAnderson Green
31.8k69 gold badges209 silver badges339 bronze badges
2
- 3 And what should your result be? An array of 3 arrays, or an array of 6 strings? – Michael Berkowski Commented May 12, 2013 at 3:17
- 1 @MichaelBerkowski The result should be an array of 3 arrays, where each of the 3 arrays is an array of strings. – Anderson Green Commented May 12, 2013 at 3:18
2 Answers
Reset to default 8Use the Array map
method to return a modified version of your array:
var newArray = theArray.map(function(v,i,a){
return v[0].split(",");
});
The function that is passed as the argument to the map
method is used to determine the values in the mapped array. As you can see, the function takes each value in the array, splits it by ma, and returns the resulting array of two strings.
The output is then:
[["Split", "each"],["string", "in"],["this", "array"]];
To make this work recursively for arrays of arbitrary depth, you can use:
var newArray = theArray.map(function mapper(v,i,a){
if(typeof v == "string"){
return v.split(",");
} else {
return v.map(mapper);
}
});
You can do this using a traditional for loop:
var theArray = [["Split,each"],["string, in"],["this","array"]];
for(var i = 0; i<theArray.length; i++) {
theArray[i] = theArray[i].split(",");
}
I'd steer clear of using the map
method, it doesn't have great support. (IE < 9 doesn't support it)