【问题标题】:What is the fastest way to categorize arrays using underscore.js?使用 underscore.js 对数组进行分类的最快方法是什么?
【发布时间】:2012-04-27 05:03:25
【问题描述】:

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

【问题讨论】:

  • for 循环有什么问题?它不会变得更快。

标签: javascript arrays mapreduce underscore.js


【解决方案1】:

好的,我找到了:

groupBy _.groupBy(list, iterator)
将集合拆分为集合,按通过 iterator 运行每个值的结果进行分组。如果 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];
    });

【讨论】:

    【解决方案2】:

    我认为,这应该更快

    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;
    }, []);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2018-10-06
      • 2013-08-08
      • 1970-01-01
      相关资源
      最近更新 更多