简体   繁体   中英

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

For a json object like this,

list=[
 {name:"hello",
  category:"verb"},
 {name:"world",
  category:"noun"}
];

What would be the fastest way to categorize the array using underscore to get this:

category=[
{id:"verb",
 list:[
  {name:"hello",
  category:"verb"}
 ]},
{id:"noun",
 list:[
  {name:"world",
  category:"noun"}
 ]}
];

It should be some kind of chained map-reduce... Of course I could do this easily using _.filter (but that would be slow), or using a for loop.

OK, I found it:

groupBy _.groupBy(list, iterator)
Splits a collection into sets, grouped by the result of running each value through iterator . If iterator is a string instead of a function, groups by the property named by iterator on each of the values.

_.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"]}

So I did it using this(I already had a list):

var listofwords=_.groupBy(doc.words, function(word){
        return word.category;
    });
    _.each(doc.lists,function(list){
        list.words=listofwords[list.name];
    });

I think, this should be faster

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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