使用underscore.js对数组进行分类的最快方法是什么?

时间:2012-04-27 05:03:25

标签: javascript arrays mapreduce underscore.js

对于像这样的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循环。

2 个答案:

答案 0 :(得分: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];
    });

答案 1 :(得分: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;
}, []);