Split an array of strings using a separator

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(","));

Answers:

Answer

Use 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 comma, 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);
    }
});
Answer

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)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.