繁体   English   中英

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

[英]What is the fastest way to categorize arrays using 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轻松做到这_.filter (但这会很慢),也可以使用for循环。

好的,我找到了:

groupBy _.groupBy(列表,迭代器)
将集合分为若干集合,并按通过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];
    });

我认为这应该更快

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM