基于多个属性对javascript对象进行排序

时间:2015-05-16 23:33:34

标签: javascript

dataSet包含javascript对象的数组。每个对象都有属性colorweight。我可以根据color对数据进行排序。不过,我想知道如何根据colorweight对数据进行排序和组合,然后将数据推送到an

换句话说,假设我有两个javascript对象数组。我想在所有dataSet中找到这对对象(color, weight)然后推送。

输入:

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"];

当前输出:

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}]

期望的输出:

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}]

这是我目前的实施

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()});
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您使用下划线,您可以使用groupBy函数来帮助您。否则你可以自己定义groupBy。

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);