0

对于这样的 json 对象,

list=[
 {name:"hello",
  category:"verb"},
 {name:"world",
  category:"noun"}
];

使用下划线对数组进行分类的最快方法是什么:

category=[
{id:"verb",
 list:[
  {name:"hello",
  category:"verb"}
 ]},
{id:"noun",
 list:[
  {name:"world",
  category:"noun"}
 ]}
];

它应该是某种链式 map-reduce ......当然我可以使用_.filter(但这会很慢)或使用for循环轻松地做到这一点。

4

2 回答 2

1

好的,我找到了:

groupBy _.groupBy(list, iterator)
将集合拆分为集合,按通过迭代器运行每个值的结果进行分组。如果迭代器是字符串而不是函数,则按迭代器命名的属性对每个值进行分组。

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}

_.groupBy(['one', 'two', 'three'], 'length');
=> {3: ["one", "two"], 5: ["three"]}

所以我用这个做了(我已经有一个列表):

var listofwords=_.groupBy(doc.words, function(word){
        return word.category;
    });
    _.each(doc.lists,function(list){
        list.words=listofwords[list.name];
    });
于 2012-04-27T05:19:25.550 回答
0

我认为,这应该更快

list = [
  {name:"hello", category:"verb"},
  {name:"world", category:"noun"}
];

var addresses = {};

var catList = _.reduce(list, function(cat, item) {
  var address = addresses[item.category];
  if(typeof address == 'undefined') {
    addresses[item.category] = address = cat.length;
    cat.push({id: item.category, list: []});
  }
  cat[address].list.push(item);
  return cat;
}, []);
于 2012-04-27T05:36:57.787 回答