Reputation: 16813
I have the following implementation and its functional
https://jsfiddle.net/9mv6w0da/
Input
dataSet[0].data= [
{color:"yellow",weight:12}
,{color:"yellow", weight:12}
,{color:"yellow", weight:12}
,{color:"red",weight:13}
,{color:"red", weight:13}
];
dataSet[1].data= [
{color:"yellow",weight:12}
,{color:"yellow", weight:12}
,{color:"red",weight:13}
,{color:"red",weight:13}
,{color:"blue",weight:11}
,{color:"blue",weight:11}
];
Current Output
an[0]=[
{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
]
an[1]=[
{color:"red",weight:13}
,{color:"red",weight:13}
,{color:"red",weight:13}
,{color:"red",weight:13}
]
an[2]=[{color:"blue",weight:11},{color:"blue",weight:11}]
I would like to add {color:null, weight:null}
when I group data from different javascript objects.
Pseudo code: dataSet[0] (color, weight)+{color:null, weight:null}+dataSet[1] (color,weight)
If you take a look at desired output, an[0]
, first three objects
comes from dataSet[0
] and the last two objects
comes from dataSet[1]
. When I am combining them, I would like to add {color:null, weight:null}
Desired Output
an[0]=[
{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:null, weight:null}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
]
an[1]=[
{color:"red",weight:13}
,{color:"red",weight:13}
,{color:null, weight:null}
,{color:"red",weight:13}
,{color:"red",weight:13}
]
an[2]=[{color:"blue",weight:11},{color:"blue",weight:11}]
Upvotes: 0
Views: 55
Reputation: 1711
You can adding extra attribute to indicate what is the array number and after that put that logic (adding extra object ) into groupby method.
var i = 0 ;
var dataSet1 = dataSet.map(function(obj){
obj.map(function(objj){
objj.arrkey = i ;
return objj;
});
i = i+1;
return obj;
});
function groupBy(arr, f) {
var result = {};
var arrKey = {} ;
arr.forEach(function(elem) {
var fElem = f(elem),
list = result[fElem] || [],
arr = arrKey[fElem] ;
if(arr === undefined){
arr = elem.arrkey;}
if(elem.arrkey != arr)
{
list.push(nullobj);
}
list.push(elem);
arrKey[fElem] = elem.arrkey;
result[fElem] = list;
});
return result;
}
Example in https://jsfiddle.net/5swdjg3f/
Upvotes: 1
Reputation: 1586
combined = data1.concat ([{color: null, weight: null}]).concat (data2)
But don't do that. Use an array of arrays where each source has its own sub-array, or better yet, write a class with a method that clearly spells out why those sets are separated, because the next guy on this code doesn't know what the null
y element indicates. He also can't group things by some other criteria without digesting your delimiters and adding his own, which will be equally hack-y.
Upvotes: 0