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

What is the fastest way to categorize arrays using underscore.js?

本文关键字:方法 js 是什么 分类 下划线 数组      更新时间:2023-09-26

对于这样的 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"}
 ]}
];

它应该是某种链式地图缩减...当然,我可以使用_.filter(但那会很慢)或使用for循环轻松完成此操作。

好的,我找到了:

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

我认为,这应该更快

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