簡體   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