If the string is certain to be secure, the simplest would be to concatenat [ and ] to the beginning and end, and then eval it.
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.parse("[" + myString + "]");
This will limit you to supported JSON data types, but given your example string, it'll work fine.
Answer from I Hate Lazy on Stack OverflowIf the string is certain to be secure, the simplest would be to concatenat [ and ] to the beginning and end, and then eval it.
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.parse("[" + myString + "]");
This will limit you to supported JSON data types, but given your example string, it'll work fine.
write your code like
var myString = "[['Item', 'Count'],['iPad',2],['Android',1]]";
and just
var arr = eval(myString);
JavaScript: How to convert a string to a 2D array - Stack Overflow
convert a string into a two-dimensional array in javascript - Stack Overflow
javascript - How to convert string into 2-dimension array? - Stack Overflow
Javascript: split string into 2d array - Stack Overflow
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"]]
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;
}
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(
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(
1, $2) {
monthArray2d.push([parseInt($1), parseInt($2)]);
})
If condensed is what you're after:
var month_array = months.split(",").map(function(x){return x.split("_")});
OK so i fixed it before i asked the question... but i did so much work i'll post it anyway.
This is the code i have now that works:
var temp = list.split(',');
questions = [[],[],[],[],[]];
for(var i = 0; i < temp.length; i++) {
questions[i%5][Math.floor(i/5)] = temp[i];
one++;
}
Thank You Barmar!!!
I'd suggest a slightly different approach, that avoids the (to my mind overly-) complex internals of the for loop:
var string = "a,b,c,d,e,1,2,3,4,5",
temp = string.split(','),
midpoint = Math.floor(temp.length/2),
output = [];
for (var i=0, len=midpoint; i<len; i++){
output.push([temp[i], temp[midpoint]]);
midpoint++;
}
console.log(output);
JS Fiddle demo.
That's not a valid string -- you're nesting single quotes inside of single quotes. However, if you convert the string into one using double quotes on the inside:
str = '[ ["Row1 of first array", "Row2 of first array"], ["Row1 of 2nd array", "Row2 of 2nd array"] ]'
then you could simply parse it as a JSON object:
arr = $.parseJSON(str); // returns a two-dimensional array
This is far, FAR safer than using eval, which should only be done when you know EXACTLY what's inside the string, and even then, it's a sign of a lazy developer. When using parseJSON, you know that you're getting either an object or an array when you're done -- when using eval, anything might happen.
I guess eval will work:
var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]");
console.log(str);
β
it seems to me that you don't have a string as an input but an array of object
you can use map to trasform that array in the shape you want
like this
const obj = [{
Location: "LOCATION_1",
x: 11.8166,
y: 122.0942
},{
Location: "LOCATION_2",
x: 11.8166,
y: 122.0942
},{
Location: "LOCATION_3",
x: 11.8166,
y: 122.0942
},
]
const locations = obj.map(({Location, x, y}) => [Location, x, y])
or you can use that array of object to populate your map
like this
obj.forEach(({Location, x, y}) => {
marker = new L.marker([x, y], { icon: iconColor(color) })
// PoPup result will be displayed here
.bindPopup(Location)
//here tool tip will be used to display the label text
.bindTooltip(Location,
{
permanent: true,
direction: 'right'
}
)
.addTo(map);
})
from your code, it looks like you just want to convert an object into an array containing arrays. I don't see the reason working with string here.
var result = Object.keys(obj).map((key) => {
return [obj[key].Location, obj[key].x, obj[key].y]
})
Hello
I have an input of a 2D array in the form of a string. And I want to turn it into a 2D array and store it.
I have tried using .replace() but itβs not working as I expected.
An example of an input is
String x = β{ {F, 40 , 40 , 2000},{L, 60 , 60 , 1000},{F, 40 , 40 , 2000}}β
And I want to turn it into an array like
String [][] y = { {βFβ , β40β , β40β , β2000β}, {βBβ ,β60β , β60β , β1000β}, {βFβ , β40β , β40β , β2000β}}
I saw some tips on using replace() and split() but I am unsure how to use them to achieve what I want or if I need another function to solve this.
Any tips to help solve this would be appreciated.
You could get the iterables from string and map numbers.
var array = ["10100", "10111", "11111", "01010"],
matrix = array.map(s => Array.from(s, Number));
console.log(matrix);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run code snippetEdit code snippet Hide Results Copy to answer Expand
If the result needs to be an array of array containing one element per character of a string, you can split each string with an empty string in a loop or map.
let res = [];
let strArr = ["10100", "10111", "11111", "01010"];
strArr.map((str) => {
res.push(str.split(''))
});
console.log(res);