I have a string of month and years:
var months= "2010_1,2010_3,2011_4,2011_7";
I want to make this into a 2d array with the year in the first position of each array and the month in the second position. In other words, I want to end up with this:
var monthArray2d = [[2010,1],[2010,3][2011,4],[2011,7]];
The way I do this currently is:
//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 that code so that I never need to use the monthArray
var?
var arr = eval("[" + myString + "]"); If you wanted greater safety, use double quotes for your strings, and use JSON. parse() in the same way. var myString = '["Item", "Count"],["iPad",2],["Android",1]'; var arr = JSON.
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("_");
You can use replace
to get 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 it:
monthArray2d = months.split(",").map(function(e) {
return e.split("_").map(Number);
})
Basically, the first function looks for year/month patterns "digits underscore digits", and stores each found substring in an array. Of course, you can use other delimiters instead of underscore. The function doesn't care about the values' delimiter (comma), so that it can be whatever. Example:
var months= "2010/1 ... 2010/3 ... 2011/4";
months.replace(/(\d+)\/(\d+)/g, function($0, $1, $2) {
monthArray2d.push([parseInt($1), parseInt($2)]);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With