Push and Unshift Operation in javascript object -
i have following dataset
input:
dataset[0]=[{data:29, color:"y"},{data:44, color:"g"}] dataset[1]=[{data:16, color:"r"},{data:23, color:"m"},{data:23, color:"b"}]
i showing information on bar chart, bar chart attempting group them. , not give me expect. http://jsfiddle.net/7dhb4jh0/1
therefore,i need have following output before feed bar chart
the logic behind desired output match length of 2 dataset adding {data:0, color:null}
there 2 things involved unshift
, push
operations
desired output:
dataset[0]=[{data:29, color:"y"},{data:44, color:"g"},{data:0, color:null},{data:0, color:null},{data:0, color:null}] dataset[1]=[{data:0, color:null},{data:0, color:null},{data:16, color:"r"},{data:23, color:"m"},{data:23, color:"b"}]
initial attempt
i have did follows, https://jsfiddle.net/s8mywm33/1/
dataset=[]; dataset[0]=[{data:29, color:"y"},{data:44, color:"g"}] dataset[1]=[{data:16, color:"r"},{data:23, color:"m"},{data:23, color:"b"}] sum1=dataset[0].length sum2=dataset[1].length for(i=0;i<sum1;i++) { dataset[1].unshift({data:0, color:null}) } for(i=0;i<sum2;i++) { dataset[0].splice(2, 0, {data:0, color:null}); } console.log(dataset[0]); console.log(dataset[1]);
however there better way it?
as per recommendations in comments, there number of ways doing this. 1 i'd recommend using dummy value (as mentioned here):
var blank = {data:0, color:null}; var dataset = []; dataset[0] = [{data:29, color:"y"}, {data:44, color:"g"}, blank, blank, blank]; dataset[1] = [blank, blank, {data:16, color:"r"}, {data:23, color:"m"}, {data:23, color:"b"}];
this makes intentions visibly clear data should where, , doesn't require code.
Comments
Post a Comment