views:

51

answers:

4

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values

  • mystring = 4|black|cat, 7|red|dog, 12|blue|fish

Here's where I want to be:
I want to end up with three arrays.

  • array1=("4","7","12")
  • array2=("black","red","blue")
  • array3=("cat","dog","fish")

I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.

+1  A: 

You want to use the split() method :

var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]

//etc...
Guillaume Lebourgeois
Once you have it like that, you could just grab the first indexes of each array to make your array one and do the same with 2 and 3. This seems like a good idea, provided I understand your question.
PFranchise
A: 

Like this?:

var values = mystring.split(',');

var arrays = new Array();

for(var i=0; i < values.length; i++) {
    var parts = values[i].split('|');
    for(var j = 0; j < parts.length;j++) {
        if(!arrays[j]) {
            arrays[j] = new Array();
        }
        arrays[j].push(parts[j]);
    }
}

Will give you an array that contains those three arrays.

Felix Kling
+4  A: 

I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:

var arr1 = [], arr2 = [], arr3 = [],
    mystring = "4|black|cat, 7|red|dog, 12|blue|fish";

mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) { 
    arr1.push($1);
    arr2.push($2);
    arr3.push($3);
}); 

Example

Andy E
+1 nice........
Felix Kling
very nice, good idea.
PFranchise
Sweet! Thanks for the help.
Kirt
+1  A: 
   var str = '4|black|cat, 7|red|dog, 12|blue|fish';

   var tmp = str.split(',');

   var firstArray = Array();
   var secondArray = Array();
   var thirdArray = Array();

   for( var i in tmp ){
        var splitted = tmp[i].split('|');
        //alert(true);
        firstArray[i]=splitted[0];
        secondArray[i]=splitted[1];
        thirdArray[i]=splitted[2];
   }
dejavu