Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string into a two-dimensional array in javascript

I'm trying to convert a string like this "10|15|1,hi,0,-1,bye,2" where the first two elements 10|15 mean something different than 1,hi,0,-1,bye,2. I would like to separate them from each other. A naive way to accomplish that would be:

value = string.split("|");
var first = value[0];
var second = value[1];
var tobearray = value[2];
array = tobearray.split(",");

(Of course, if you know a way to do this in a better way, I'd be glad to know). However, array is an array which contains array[0]=1, array[1]=hi, array[2]=0, array[3]=-1, etc. However, I want to obtain a two dimensional array such as

array[0][0]=1, array[0][1]=hi, array[0][2]=0
array[1][0]=-1, array[1][1]=bye, array[1][2]=2

Is there any way to do that?

Thanks

like image 312
Robert Smith Avatar asked Mar 02 '11 05:03

Robert Smith


People also ask

How do I convert a string to a 2D array?

To convert a string into a two-dimensional array, you can first use the Split() method to split the string into Int-type values and store them in a one-dimensional array. Then read the values in a one-dimensional array and store them in a two-dimensional array.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Are there 2D arrays in JavaScript?

Technically, there is no two-dimensional array in JavaScript. JavaScript supports 2D arrays through jagged arrays – an array of arrays.

What is a 2D array JavaScript?

The two-dimensional array is a collection of items which share a common name and they are organized as a matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create an array of one-dimensional array objects.


2 Answers

The first two elements (10|15) can be extracted beforehand. After that you're left with:

var a = "1,hi,0,-1,bye,2";

Let's splice until we're left with nothing:

var result = [];

a = a.split(','); 

while(a[0]) {
    result.push(a.splice(0,3));
}

result; // => [["1","hi","0"],["-1","bye","2"]]
like image 66
James Avatar answered Oct 15 '22 16:10

James


function getMatrix(input_string) 
{
    var parts = input_string.split('^');
    for (var t=0; t<parts.length; t++)
    {
        var subparts = parts[t].split('*');

        parts[t] = subparts.splice(0,subparts.length);              
    }

    return parts;
}
like image 28
Abdel1 O. Avatar answered Oct 15 '22 17:10

Abdel1 O.