Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(","));
like image 626
Anderson Green Avatar asked Dec 20 '22 05:12

Anderson Green


2 Answers

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);
    }
});
like image 102
Asad Saeeduddin Avatar answered Jan 02 '23 01:01

Asad Saeeduddin


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)

like image 27
Elliot Bonneville Avatar answered Jan 02 '23 00:01

Elliot Bonneville