convert a string into a two-dimensional array in javascript -
i'm trying convert string "10|15|1,hi,0,-1,bye,2" first 2 elements 10|15 mean different 1,hi,0,-1,bye,2. separate them each other. naive way accomplish be:
value = string.split("|"); var first = value[0]; var second = value[1]; var tobearray = value[2]; array = tobearray.split(","); (of course, if know way in better way, i'd glad know). however, array array contains array[0]=1, array[1]=hi, array[2]=0, array[3]=-1, etc. however, want obtain 2 dimensional array such
array[0][0]=1, array[0][1]=hi, array[0][2]=0 array[1][0]=-1, array[1][1]=bye, array[1][2]=2 is there way that?
thanks
the first 2 elements (10|15) can extracted beforehand. after you're left with:
var = "1,hi,0,-1,bye,2"; let's splice until we're left nothing:
var result = []; = a.split(','); while(a[0]) { result.push(a.splice(0,3)); } result; // => [["1","hi","0"],["-1","bye","2"]]
Comments
Post a Comment