Push and Unshift Operation in javascript object

I have the 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 am showing this information on bar chart, however bar chart attempting to group them. And it does not give me what I expect. http://jsfiddle.net/7dhb4jh0/1

Therefore,I need to have the following output before I feed my bar chart

The logic behind the desired output to match the length of two dataset by adding {data:0, color:null} There are two things involved unshift and 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 it as 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 is there a better way to do it?


As per my recommendations in the comments, there are a number of ways you could be doing this. The one I'd recommend is just using a dummy value (as I 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 your intentions visibly clear for what data should be where, and doesn't require that much extra code.

链接地址: http://www.djcxy.com/p/19370.html

上一篇: KnockoutJS追加到observableArray的开头

下一篇: 在javascript对象中推送和不移位操作