Javascript: split a string into a 2d array

I have a line of the month and years:

var months= "2010_1,2010_3,2011_4,2011_7";

I want to do this in a 2d array with a year in the first position of each array and a month in the second position. In other words, I want to end up with:

var monthArray2d = [[2010,1],[2010,3][2011,4],[2011,7]];

I am currently doing this:

//array of selected months
var monthArray = months.split(",");

//split each selected month into [year, month] array
var monthArray2d = new Array();
for (var i = 0; i < monthArray.length; i++) {
    monthArray2d[i] = monthArray[i].split("_");

Is there a way to condense this code so I never have to use monthArrayvar?

+6
source share
4 answers

You can use replaceto get a more compact code:

var months= "2010_1,2010_3,2011_4,2011_7";
var monthArray2d = []

months.replace(/(\d+)_(\d+)/g, function($0, $1, $2) {
    monthArray2d.push([parseInt($1), parseInt($2)]);
})

or map, if your target browser supports this:

monthArray2d = months.split(",").map(function(e) {
    return e.split("_").map(Number);
})

, / " " . , . (), . :

var months= "2010/1 ... 2010/3 ... 2011/4";
months.replace(/(\d+)\/(\d+)/g, function($0, $1, $2) {
    monthArray2d.push([parseInt($1), parseInt($2)]);
})
+10

, :

var month_array = months.split(",").map(function(x){return x.split("_")});
+6

JavaScript - , , . , _ .

. :

var months= "2010_1,2010_3,2011_4,2011_7";

var monthArray = months.split(",");

for (var i = 0; i < monthArray.length; i++) {
   monthArray[i] = monthArray[i].split("_");
}

console.log(monthArray);

, , monthArray. , !

+3

- , , , -

:

var s= "2010_1,2010_3,2011_4,2011_7",

A= [], rx=/(\d+)_(\d+)/g;

while((M= rx.exec(s))!= null){
    A.push([M[1], M[2]]);
}


/*  returned value: (Array)
[[2010,1],[2010,3],[2011,4],[2011,7]]
*/
+1

All Articles