使用Lotash进行分组

2022-03-09 00:00:00 javascript lodash

我有一个对象数组,如下所示:

var data = [
  {
    "count": 1, 
    "make": "ALFA ROMEO", 
    "model": "GIULIETTA DIESEL - 2010"
  }, 
  {
    "count": 2, 
    "make": "AUDI", 
    "model": "A1 DIESEL"
  }, 
  {
    "count": 1, 
    "make": "AUDI", 
    "model": "A1 SPORTBACK DIESEL"
  }, 
  {
    "count": 2, 
    "make": "AUDI", 
    "model": "A3 DIESEL - 2012"
  }, 
  {
    "count": 3, 
    "make": "Volkswagen", 
    "model": "Golf"
  }, 
  {
    "count": 3, 
    "make": "Ford", 
    "model": "Escord"
  }, 
  {
    "count": 2, 
    "make": "Opel", 
    "model": "Zafira"
  }
]

我要group bymake,然后获得计数最高的三个Make和要显示为其他的睡觉。

例如,我想获得:

var result = [
    {
       "brand": "Audi",
       "count": 5
     },
     {
       "brand": "Volkswagen",
       "count": 3
     },
     {
       "brand": "Ford",
       "count": 3
     },
     {
       "brand": "Other",
       "count": 3
     }
]

我不知道怎么开始。有什么帮助吗?


解决方案

使用LOCASH

创建一个旅店连锁店。按make使用_.groupBy(),然后使用_.map()结果和_.sumBy()属性。使用_.values()转换回数组,使用_.orderBy()降序排序,然后使用_.value()完成链。Split将结果分成两个数组,并使用Reduce将第二个数组(低集合计数)相加:

var data = [{"count":1,"make":"ALFA ROMEO","model":"GIULIETTA DIESEL - 2010"},{"count":2,"make":"AUDI","model":"A1 DIESEL"},{"count":1,"make":"AUDI","model":"A1 SPORTBACK DIESEL"},{"count":2,"make":"AUDI","model":"A3 DIESEL - 2012"},{"count":3,"make":"Volkswagen","model":"Golf"},{"count":3,"make":"Ford","model":"Escord"},{"count":2,"make":"Opel","model":"Zafira"}];

var counts = _(data)
  .groupBy('make')
  .map(function(g, key) { return {
      make: key,
      count: _.sumBy(g, 'count')
  };})
  .values()
  .orderBy('count', 'desc')
  .value();
  
var result = counts.slice(0, 3).concat({
  brand: 'other',
  count: counts.slice(3).reduce(function(s, { count }) { return s + count; }, 0)
})
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

使用ES6

使用Array#reduce迭代,将所有make count值收集到Map中的一个对象,然后获取map values iterator和spread以获得数组,并进行降序排序。Split将结果分成两个数组,并使用Reduce将第二个数组(低集合计数)相加:

const data = [{"count":1,"make":"ALFA ROMEO","model":"GIULIETTA DIESEL - 2010"},{"count":2,"make":"AUDI","model":"A1 DIESEL"},{"count":1,"make":"AUDI","model":"A1 SPORTBACK DIESEL"},{"count":2,"make":"AUDI","model":"A3 DIESEL - 2012"},{"count":3,"make":"Volkswagen","model":"Golf"},{"count":3,"make":"Ford","model":"Escord"},{"count":2,"make":"Opel","model":"Zafira"}];

const counts = [...data.reduce((m, { make, count }) => {
  const item = m.get(make) || { make, count: 0 };
  
  item.count += count;

  return m.set(make,  item);
}, new Map()).values()].sort((a, b) => b.count - a.count);

const result = counts.slice(0, 3).concat({
  brand: 'other',
  count: counts.slice(3).reduce((s, { count }) => s + count, 0)
})

console.log(result);

相关文章