I have this string
foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]";
How can I convert this into a JavaScript array (likely without splitting the string, because there are over 16,000 values in the array and I want to save time)?
Did you mean to merge all the sub-arrays into one? If yes, you could try with the following snippet:
var foo = '[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]'; var list = JSON.parse(foo); var combined = new Array(); for (var counter = 0; counter < list.length; counter++) { for(var index = 0; index < list[counter].length; index++) { combined.push(list[counter][index]); } } console.log(combined);
You can use JSON.parse
to convert the string into array, then use .concat
method to merge the arrays into one.
DEMO
var foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]"; var output = JSON.parse(foo); var merged = [].concat.apply([], output); console.log(merged);
Make use of reduce function available on array
var foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]"; var nested_array = JSON.parse(foo); var output = nested_array.reduce(function(prev, curr) { return prev.concat(curr); }); console.log(output)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.