coure2011
coure2011

Reputation: 42454

Splitting to 2D array

How I can split a string into 2D array. String is like

1c2c3r4c5c6r6c8c9

array should be like

[[1,2,3],
[4,5,6],
[7,8,9]]

Upvotes: 2

Views: 1191

Answers (4)

Jimmy Huang
Jimmy Huang

Reputation: 4312

var str = "1c2c3r4c5c6r6c8c9";
var result = [];
var group = str.split("r");
for(i in group) {result.push(group[i].split("c"))};

result should be what you want.

Upvotes: 2

dheerosaur
dheerosaur

Reputation: 15172

You can use the map method on Array

var s = "1c2c3r4c5c6r6c8c9";
var rows = s.split("r");
result = rows.map(function (x) {
    return x.split('c');
}));

map is introduced in ECMAScript5 and is not supported in older browsers. But, there is a decent work-around here

Upvotes: 3

Fabien Ménager
Fabien Ménager

Reputation: 140195

This should work:

var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/g);

for (var i = 0; i < rows.length; i++) {
    var cells = rows[i].split(/c/g);
    for (var j = 0; j < cells.length; j++) {
        cells[j] = parseInt(cells[j]);
    }
    rows[i] = cells;
}

Upvotes: 1

sjngm
sjngm

Reputation: 12861

var src = "1c2c3r4c5c6r6c8c9";
var rows = src.split(/r/);

for (var i = 0; i < rows.length; i++)
    rows[i] = rows[i].split(/c/);

Please note that I didn't test this so it might contain a syntax error or something...

Upvotes: 3

Related Questions