The dataSet
contains arrays of javascript objects. Each object has the property color
and weight
. I am able sort the data based on the color
. However I would like to know how to sort and combine data based on color
and weight
together and then push data to an
In other words, let say I have two arrays of javascript objects. I would like to find the pair of these objects (color, weight)
in all dataSet then push.
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}
];
colorMap=["red","green","blue","yellow","pink","black"];
Current output:
an[0]=[
{color:"yellow",weight:12}
,{color:"yellow",weight:12}
,{color:"yellow",weight:12}
]
an[1]=[{color:"red",weight:13},{color:"red",weight:13}]
an[2]=[{color:"yellow",weight:12},{color:"yellow",weight:12}]
an[3]=[{color:"red",weight:13},{color:"red",weight:13}]
an[4]=[{color:"blue",weight:11},{color:"blue",weight:11}]
Desired 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}]
Here is my current implementation
for (i = 0; i < dataSet.length; i++) {
for (j = 0; j < self.colorMap.length; j++) {
var d = dataSet[i].data.filter(function (x) { return x.color == self.colorMap[j] });
if (d.length > 0) {
an.push({ data: d, color: d[0].color, name:d[0].weight.toString()});
}
}
}
If you use underscore you can use the groupBy function to help you here. Otherwise you can define groupBy yourself.
function groupBy(arr, f) {
var result = {};
arr.forEach(function(elem) {
var fElem = f(elem),
list = result[fElem] || [];
list.push(elem);
result[fElem] = list;
});
return result;
}
function objToArray(obj) {
var result = [];
for(k in obj) {
result.push(obj[k]);
}
return result;
}
var dataSet = [];
dataSet[0]= [{color:"yellow",weight:12},{color:"yellow", weight:12},{color:"yellow", weight:12},{color:"red",weight:13},{color:"red", weight:13}];
dataSet[1]= [{color:"yellow",weight:12},{color:"yellow", weight:12},{color:"red",weight:13},{color:"red",weight:13},{color:"blue",weight:11},{color:"blue",weight:11}];
var allData = dataSet.reduce(function(a, b) { return a.concat(b) });
var grouped = objToArray(groupBy(allData, function(data) { return data.color + "#" + data.weight }));
console.log(grouped);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다