user2898733
user2898733

Reputation: 19

javascript split without losing first element (not RegEx)

I have a string containing ones and zeros split by "," and ";".

var x = "1,1,0;1,0,0;1,1,1;"; x.split(";");

This wil output an array with just two strings: 1,0,0 and 1,1,1.
What I want is to put all of these numbers in a two dimensional array:
1 1 0
1 0 0
1 1 1
If there is a smarter way than just split the string, please let me know.
Otherwise, please tell me how to fix the problem above.

Upvotes: 0

Views: 394

Answers (2)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

given the string:

  var x = "1,1,0;1,0,0;1,1,1";

you can get a two dimensional array of zeros and ones this way:

var st = x.split(";")
var twoDimensionalArray = st.map(function(k){
    return k.split(","); 
});

of course, thanks to JS method chaining, you can do the whole thing this way:

var twoDimTable = x.split(";").map(function(k){
  return k.split(","); 
});

the result:

 [
   ["1","1","0"],
   ["1","0","0"],
   ["1","1","1"]
 ]

well, to get the result as

 [
    [1,1,0],
    [1,0,0],
    [1,1,1]
 ]

you can do a loop and for each value k within the array do k = +k; and you will get numbers instead of strings. However, JavaScript will do the casting for you when you use these values within an operation with a number.

Upvotes: 2

chiliNUT
chiliNUT

Reputation: 19573

  1. You need to put quotes around your string.
  2. Commentors are correct, your array contains all 3 strings. did you forget that array indices start at 0, not 1?
  3. x.split does not modify x, it returns an array

You probably want something like this

    var str = "1,1,0;1,0,0;1,1,1";
    var arr = str.split(";");

    for (var i = 0, len = arr.length; i < len; i++)
    {
        arr[i] = arr[i].split(",");
    }

and to verify the result

    for (var i = 0, len = arr.length; i < len; i++)
    {
        for (var j = 0, len2 = arr[i].length; j < len2; j++)
        {
            document.write(arr[i][j] + " | ");
        }

        document.write("<br>");
    }

Upvotes: 6

Related Questions